As title. I try to set component state from child through callback given by parent. Demo is in https://codepen.io/jadecubes/pen/wvYxKEL
The callback looks like
A = () => {
const [info, setInfo] = useState(["Hello world."]);
return (
<>
<B
onChange={() => {/*I am callback*/
info.length = 0;
info.push("Hey!");
setInfo(info);
}}
/>
<h1>{info}</h1>
</>
);
};
Clicking button doesn’t change the text. But if it’s something like below, it changes normally.
A = () => {
const [info, setInfo] = useState(["Hello world."]);
return (
<>
<B
onChange={() => {/*I am callback*/
setInfo(['hey']);
}}
/>
<h1>{info}</h1>
</>
);
};
Any suggestions are welcome.
2
Answers
You can’t push items in the array that is stored in react state with push method because arrays store in react state are immutable. Here is the updated code. Try that:-
You can read how to update arrays more in details in react docs.
Hope it will be helpful.
React state are immutable.
You should not aim to mutate the state directly by calling methods like push, pop
You should use methods that return new arrays like concat, …etc
Check React documentations below:
https://react.dev/learn/updating-arrays-in-state