0

In a class-based component when one would set the state, it would take the argument of the new state and sometimes one could fire another function within it. In a functional-based component, using hooks, how can I accomplish the same goal?

// class-based componenet example:

state = {
  count: 0
}

this.setState({
  count: count +1
}, () => someFunction())


// functional-based componenet example:(how to fire someFunction() when the state is set like in the class-based componenet?)

const [count, setCount] = useState(0)

setCount(count +1)

I'm aware that hooks don't take a second argument but can something similar be done?

ravibagul91
  • 20,072
  • 5
  • 36
  • 59
steelyphil
  • 91
  • 1
  • 1
  • 7

1 Answers1

1

I think the useEffect hook would help you here. It basically acts as a componentDidUpdate:

  useEffect(() => {
    doSomething();
  }, [count]);

The second parameter means that the effect / function will only fire if count changes.

cullanrocks
  • 457
  • 4
  • 16
  • So would I be able to useEffect twice with the same function, first time would be for when my page loads. And the second time would be for when the dependency is met? – steelyphil Aug 13 '19 at 16:16
  • You can have as many useEffects as you'd like, just know that they will be called whenever a state change is detected. – cullanrocks Aug 13 '19 at 16:20