0

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!

3 Answers 3

2

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>
        </>
    )
}
Sign up to request clarification or add additional context in comments.

1 Comment

Hi, thank you for your answer. I updated the code and it's still not calling the useEffect. Is there any other reasons that could be causing this?
0

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.

1 Comment

I see. I think there must be something else that is messing with my code and preventing the useEffect to run then. Thank you for your insights!
0

Solution to my own problem: There wasn't anything wrong with my code above. However, in my codebase, I didn't realize that I changed the value of the object but not the reference. Now that I assigned a new reference for each value change, it works perfectly.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.