Home > other >  How to call useEffect after updating state in a component
How to call useEffect after updating state in a component

Time:12-27

I am having a little trouble calling a useEffect using a setstate that I passed as a prop to a child component. I am not sure this is the way to do this.

The code goes something like this:

const Parent = () => {
const [state, setState] = useState()
useEffect(() => {
    console.log ('state updated');
}, [state])

return (
    <>
    <Child state={state} setState = {setState}/>
    </>
)}

const Child = (props) => {
const update = () => {
    props.setState("updated");
}
return(
    <>
    <button onClick={update}></button>
    </>
)}

In this case, I expect the useEffect to run when the button is clicked but it does not. How do I fix it or is there a better way of doing this. Note that the two components are different files.

Thanks in advance!

CodePudding user response:

You need to pass setState as a prop to Child component. Previously you passed only state prop.

const Parent = () => {
    const [state, setState] = useState()

    useEffect(() => {
        console.log ('state updated');
    }, [state])

    return (
        <>
            <Child setState={setState}/>
        </>
    )
}

const Child = (props) => {
    const update = () => {
        props.setState("updated");
    }

    return(
        <>
            <button onClick={update}></button>
        </>
    )
}

CodePudding user response:

I've tested your code here https://codesandbox.io/s/dank-cherry-n5ygr?file=/src/App.js and it works as expected.

useEffect is called only once because subsequent states have the same value 'updated'. Please note that useEffect is also called when the component is mounted so you should expect to see 2 console.log after you've clicked the button.

  • Related