Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

React: useState is not resetting to initial state [duplicate]

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

like image 958
Poojan Bedi Avatar asked Oct 24 '25 05:10

Poojan Bedi


2 Answers

useState is working as intended, the value passed to it is only its initialState 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 new initialState:

<CheckListItem
  initialIsChecked={initialIsChecked}
  {/* When `initialIsChecked` changes, a new
    * `CheckListItem` instance will be created` */}
  key={initialIsChecked}
/>
like image 124
Ross Allen Avatar answered Oct 26 '25 17:10

Ross Allen


There's a typo in setChaecked(ev.target.checked); change it to setChecked(ev.target.checked);

And also try this code

const CheckListItem = ({ label, onChangeEventHandler, isChecked, index }) => {
  const localOnChangeHandler = (ev) => {
    if (typeof onChangeEventHandler === "function") {
      onChangeEventHandler(index, ev.target.checked);
    }
  };

  return (
    <li key={index}>
      <label>
        <input
          type="checkbox"
          checked={isChecked}
          onChange={localOnChangeHandler}
        />
        {label}
      </label>
    </li>
  );
};
like image 35
Antony Jude Shaman Avatar answered Oct 26 '25 18:10

Antony Jude Shaman