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;
constuseValidateContent = initState => {
const [valid, setValid] = useState(initState);
const [errorMsg, setErrorMsg] = useState("");
constvalidate = () => {
setValid(false);
setErrorMsg("Some error found");
};
return [valid, validate, errorMsg];
};
functionParentComp() {
const [contentIsValid, validate, contentError] = useValidateContent(true);
constinitValidate = () => {
// values before running validateconsole.log("valid", contentIsValid);
console.log("error", contentError);
validate();
// values after running validateconsole.log("valid", contentIsValid);
console.log("error", contentError);
};
return (
<div><buttononClick={initValidate}>initValidate</button>
contentIsValid: {contentIsValid.toString()}, contentError: {contentError}
</div>
);
}
ReactDOM.render(<ParentComp />, document.getElementById("root"));
<scriptsrc="https://unpkg.com/react@16/umd/react.development.js"></script><scriptsrc="https://unpkg.com/react-dom@16/umd/react-dom.development.js"></script><divid="root"></div>
Post a Comment for "Component Local State Not Updating With React Custom Hooks"