The useEffect Hook

Defining the Effect Hook

  • The effect hook performs side effects
  • Specifically, it performs side effects in functional components
  • It is close replacement for the following:

    • componentDidMount
    • componentDidUpdate
    • componentWillUnmount

What Does useEffect Do?

  • This hook tells React what to do after each render
  • React will remember the function you passed
  • This function is referred to as an effect
  • Then, React calls the effect after performing the DOM updates
  • In this effect, we may call things like:

    • Setting the document title
    • Fetching data
    • Calling some imperative API

Does useEffect Run after Every Render?

  • By default, this hook runs after every render
  • Specifically, it runs after both mouting and updating
  • Instead of thinking in terms of mounting and updating, it's easier to think of effects happening after render
  • React guarantees the DOM is updated once it runs the effects

Illustrating Side Effects without Hooks

  • Without using the useEffect hook, we must use class components to implement side effects
  • The following is an example of this:
class Counter extends Component {
  contructor(props) {
    super(props);
    this.state = {
      count: 0
    }
  }

  componentDidMount() {
    let title = document.title;
    title = `Clicked ${this.state.count} times`
  }

  componentDidUpdate() {
    let title = document.title;
    title = `Clicked ${this.state.count} times`
  }

  addCount = () => {
    this.setState({
      count: this.state.count+1
    })
  }

  render() {
    let
    return (
      <div>
        <button onclick={addCount}>
          Click {this.state.count} times
        </button>
      </div>
    )
  }
}

Illustrating Side Effects with useEffect

  • When specifying useEffect, we request execution of the function passed as an argument
  • Specifically, this function is executed every time the component renders
  • This hook is placed inside the component in order to easily access the component's state and props without extra code
  • The following interprets the above example using the useEffect hook:
function Counter() {
  const [count, setCount] = useState(0);

  // Changes title during mounting and updating
  useEffect(() => {
    document.title = `You clicked ${count} times`
  })

  return (
    <div>
      <button onclick={() => setCount(count+1)}>
        Click {count} times
      </button>
    </div>
  )
}

References

Previous
Next

The useState Hook

Conditional Rendering with Hooks