patternjavascriptreactCritical
Why is useState not triggering re-render?
Viewed 0 times
usestatewhyrendernottriggering
Problem
I've initialized a state that is an array, and when I update it my component does not re-render. Here is a minimal proof-of-concept:
Based on this code, it seems that the input should contain the number 0 to start, and any time it is changed, the state should change too. After entering "02" in the input, the App component does not re-render. However, if I add a setTimeout in the onChange function which executes after 5 seconds, it shows that numbers has indeed been updated.
Any thoughts on why the component doesn't update?
Here is a CodeSandbox with the proof of concept.
function App() {
const [numbers, setNumbers] = React.useState([0, 1, 2, 3]);
console.log("rendering...");
return (
{numbers.map(number => (
{number}
))}
{
let old = numbers;
old[0] = 1;
setNumbers(old);
}}
/>
);
}Based on this code, it seems that the input should contain the number 0 to start, and any time it is changed, the state should change too. After entering "02" in the input, the App component does not re-render. However, if I add a setTimeout in the onChange function which executes after 5 seconds, it shows that numbers has indeed been updated.
Any thoughts on why the component doesn't update?
Here is a CodeSandbox with the proof of concept.
Solution
You're calling
One easy way to avoid this is by spreading the array into a new array:
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])Code Snippets
setNumbers([...old])Context
Stack Overflow Q#56266575, score: 564
Revisions (0)
No revisions yet.