Home > Enterprise >  How to update a useState hook in a child component?
How to update a useState hook in a child component?

Time:10-07

I am pretty new to React Hooks and could not understand how to place a useState() function inside a child component, both in a child's body and in a child's inner function, like this:

function Parent () {
    const [counter, setCounter] = React.useState();
    return (
    <Child counter={counter} setCounter={setCounter}/>
  )
}

function Child (props) {
    const counter = props.counter;
  const setCounter = props.setCounter;
  React.useEffect(() => {
    setCounter(0);
  })
  const increament = () => {
      setCounter(1);
  }
    return (
  <div> {counter} <button onClick={increament}>Increase Count</button> </div>
  )
}

My code keeps reupdating the state to 0. What's wrong?

Please check my fiddle.

Thanks!

CodePudding user response:

You missed the second argument in useEffect.
useEffect will trigger on every render if the second argument is not there and it will reset the changed value back to 0 again

React.useEffect(() => {
  setCounter(0);
},[])

Full code sample

 function Parent () {
    const [counter, setCounter] = React.useState();
    return (
    <Child counter={counter} setCounter={setCounter}/>
  )
}

function Child (props) {
    const counter = props.counter;
  const setCounter = props.setCounter;
  React.useEffect(() => {
    setCounter(0);
  }, [])
  const increament = () => {
      setCounter(counter   1);
  }
    return (
  <div> {counter} <button onClick={increament}>Increase Count</button> </div>
  )
}

CodePudding user response:

Your code works: https://codesandbox.io/s/billowing-bird-p9xzp?file=/src/App.js

But there are several things to consider here:

1- you can initialize the state to 0 in const [counter, setCounter] = React.useState(0);

2- You dont need useEffect in child component

CodePudding user response:

Your useEffect hook is missing a dependency array, so it is being called every time the child component renders. This means every time you click increment, the state gets set to 1, but then your useEffect immediately fires again and resets the count to 0. Fix this by placing an empty dependency array at the end of your useEffect (this means it will only fire once when the component is first mounted):

  React.useEffect(() => {
    setCounter(0);
  }, [])

Also if you are want your button to actually increment the count by one every time you have to setCounter to 1 the previous state, otherwise the counter will jsut stay at 1 everytime it is clicked:

  const increament = () => {
      setCounter(prevCounter => prevCounter   1);
  }
  • Related