Skip to content Skip to sidebar Skip to footer

Component Local State Not Updating With React Custom Hooks

I'm just starting to use react hooks and I'm having some issues when using custom hooks. It's probably lack of understanding but here's what I'm attempting My Custom hook: import R

Solution 1:

Updating state with hooks is asynchronous just like setState in a class component is, and since the state is not mutated contentIsValid and contentError will still refer to the stale old state and not the new state.

If you render your state variables you will see that your code works as expected.

const { useState } = React;

const useValidateContent = initState => {
  const [valid, setValid] = useState(initState);
  const [errorMsg, setErrorMsg] = useState("");

  const validate = () => {
    setValid(false);
    setErrorMsg("Some error found");
  };

  return [valid, validate, errorMsg];
};

function ParentComp() {
  const [contentIsValid, validate, contentError] = useValidateContent(true);

  const initValidate = () => {
    // values before running validate
    console.log("valid", contentIsValid);
    console.log("error", contentError);
    validate();
    // values after running validate
    console.log("valid", contentIsValid);
    console.log("error", contentError);
  };

  return (
    <div>
      <button onClick={initValidate}>initValidate</button>
      contentIsValid: {contentIsValid.toString()}, contentError: {contentError}
    </div>
  );
}

ReactDOM.render(<ParentComp />, document.getElementById("root"));
<script src="https://unpkg.com/react@16/umd/react.development.js"></script>
<script src="https://unpkg.com/react-dom@16/umd/react-dom.development.js"></script>

<div id="root"></div>

Post a Comment for "Component Local State Not Updating With React Custom Hooks"