How to fully replace one array by new in react useState();
by just setting it setState(newValue);
Let's go step by step:
[...newValue] this creates a copy of newValue. But newValue is already a new value (I'd assume by the name). So we don't need to copy the array.
which leaves us with setColors(prevState => newValue). but since we don't interact with prevState we don't need the function at all and can just pass the newValue.
now we're at const onChangeColors = (newValue) => { setColors(newValue); } but do we really need onChangeColors? All it does is forward the argument it gets to setColors. We can simply replace it: const onChangeColors = setColors;
onChange={newValue => onChangeColors(newValue)} that's the same as the step before, this function is also just forwarding the argument.
which effectively leaves us with: <ColorPicker colors={colors} onChange={setColors} />
But that's for this special case where onChange passes the new value, not like an event-object and you want to replace the old state, not append to it or something.
const [colors, setColors] = useState(['#FF9A00', '#6276d5', '#18B8FB']);
return (<div style={{ width: '500px', margin: 'auto' }}>
<h2>Current Color:</h2>
{
colors.map((color, index) => (<p key={index}>{color}</p>))
}
<ColorPicker colors={colors} onChange={setColors} />
</div>);