The useState() hook in react allows us to declare a state variable that persists during the re-render cycles. If we want to re-render the component then we can easily do so by calling the setState() function which is obtained by destructuring the array returned as a result of calling the useState() hook.
The NoStateCounter component has a first initial render but it never re-renders because no component props or state ever changes. As a result, the count value changes when the button is clicked, but only when useState is used will the component re-render to show the current value of count .
If React fails to do re-render components automatically, it's likely that an underlying issue in your project is preventing the components from updating correctly.
The answer: They're just queues setState , and React. useState create queues for React core to update the state object of a React component. So the process to update React state is asynchronous for performance reasons. That's why changes don't feel immediate.
You're calling setNumbers
and passing it the array it already has. You've changed one of its values but it's still the same array, and I suspect React doesn't see any reason to re-render because state hasn't changed; the new array is the old array.
One easy way to avoid this is by spreading the array into a new array:
setNumbers([...old])
You need to copy numbers
like so let old = [...numbers];
useState
doesn't update the value only if it has changed so if it was 44
and it became 7
it will update. but how can it know if an array or object have changed. it's by reference so when you do let old = numbers
you are just passing a reference and not creating a new one
Others have already given the technical solution. To anyone confused as to why this happens, is because setSomething() only re renders the component if and only if the previous and current state is different. Since arrays in javascript are reference types, if you edit an item of an array in js, it still doesn't change the reference to the original array. In js's eyes, these two arrays are the same, even though the original content inside those arrays are different. That's why setSomething() fails do detect the changes made to the old array.
Note that if you use class components and update the state using setState() then the component will always update regardless of whether the state has changed or not. So, you can change your functional component to a class component as a solution. Or follow the answers provided by others.
You can change state like this
const [state, setState] = ({})
setState({...state})
or if your state is Array you can change like this
const [state, setState] = ([])
setState([...state])
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