skip to Main Content

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


  1. 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>
      );
    };
    
    Login or Signup to reply.
  2. 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}
    />
    
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search