I am trying to re-render the checked state of below component, even though the isChecked state comes as false, the useState is not updating to the set prop value, instead it maintains the old state.
const CheckListItem = ({ label, onChangeEventHandler, isChecked, index }) => {
const [checked, setChaecked] = useState(isChecked || false);
console.log(`${label} checked => `, isChecked); \ false
console.log(`${label} checked => `, checked); \ true || maintaining the old state.
const localOnChangeHandler = (ev) => {
if (typeof onChangeEventHandler === "function") {
setChaecked(ev.target.checked);
onChangeEventHandler(index, ev.target.checked);
}
};
useEffect(() => {
console.log(`in useEffect ${label} checked => `, isChecked);
setChaecked(isChecked);
}, [isChecked, label]);
return (
<li key={index}>
<label>
<input
type="checkbox"
checked={checked}
onChange={localOnChangeHandler}
/>
{label}
</label>
</li>
);
};
checked
should have the correct value which is set in the isChecked
prop
2
Answers
There’s a typo in
setChaecked(ev.target.checked);
change it tosetChecked(ev.target.checked);
And also try this code
useState
is working as intended, the value passed to it is only itsinitialState
and if even if that value changes it will not update the stored value.See React’s docs about Resetting all state when a prop changes – rather than complicate your code you can pass a
key
from the parent to create a new component instance and thereby pass a newinitialState
: