I'm using React Sortable HOC to move items around. My initial state is an empty array and I need to update the state with a function from React Sortable.
This is the original snippet from React Sortable HOC
onSortEnd = ({oldIndex, newIndex}) => {
this.setState(({items}) => ({
items: arrayMove(items, oldIndex, newIndex),
}));
};
My state and function look like this
const [colors, setColors] = useState([])
function onSortEnd({ oldIndex, newIndex }) {
setColors([...colors, ({ colors }) => ({
colors: arrayMove(colors, oldIndex, newIndex)
})]);
};
What ends up happening is no errors, but more colors get added when I attempt to arrange any existing color.
Rules for using useState You'll get an error. The first rule means that, even inside functional components, you shouldn't call useState in loops, conditions, or nested functions because React relies on the order in which useState functions are called to get the correct value for a particular state variable.
Equipped with these solutions, you can store and mutate functions in state hooks without mysterious crashes and cryptic error messages. However, you should take care not to overuse it.
With the useState hook, you can pass a function as an argument to initialize the state lazily. As discussed, the initial value is needed only once at the first render.
UseState works just as class component's state Depending on how frequently your application's data changes, it's a good idea to break state into multiple variables. As a rule of thumb, it's best to keep each state separate so that it's easy to update and submit the data.
Based on the requirement mentioned, I think you don't need the callback format for setState
and you can simply do
const [colors, setColors] = useState([])
function onSortEnd({ oldIndex, newIndex }) {
const newColors = arrayMove(colors, oldIndex, newIndex);
setColors(newColors);
};
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With