React's useEffect( hook

We already saw the useState( hook, but there is another hook that's important useEffect(.

The useEffect hook takes two arguments:

  • A function to call when something happens
  • An array of the props / state variables to monitor for changes

Example:

React.useEffect(() => {
  console.log('Something happened')
})

Anytime React rerenders, once the rerender is complete the function is called and 'Something happened' prints to the screen.

Firing useEffect on first render:

React.useEffect(() => {
  console.log('Something happened')
}, [])

This tells React to fire our function only on the first render (mount), this works because there are no props or state this effect depends on: [].

Depending on a prop:

React.useEffect(() => {
  console.log('Something happened')
}, [props.name])

This effect function only fires if prop.name changes.

useEffect is a bit confusing (for all of us!), so just keep this at the back of your mind and don't worry too much about it for now!