Step 7

Let's revisit the code where we employed useEffect:

useEffect(() => {
  document.body.addEventListener("keydown", onKeyDown);
}, []);

You've learned about lifecycle methods in class components. Those methods allow you to bind actions at specific stages of a component's life cycle, such as "after a component mounts" or after it "re-renders." The technical name for these actions is "side effects," a term borrowed from functional programming.

With the useEffect Hook, you can respond to lifecycle events directly inside function components. You noticed we have replaced componentDidMount with useEffect.

The general syntax of useEffect follows:

useEffect(effectFunction, arrayDependencies);

The effectFunction is where you perform the side effects. Finally, the arrayDependencies is an array that can tell the Hook to skip applying the effect only until in certain conditions.

If you want to run an effect only once (on mount), you can pass an empty array ([]) as the dependency.

If you forget to provide the empty array ([]), the effectFunction runs on every re-rendering.

If you want to fetch data from an external API, you can do so using useEffect. For example, consider the following lifecycle method:

componentDidUpdate(prevProps) {
  if (this.props.blogPostId !== prevProps.blogPostId) {
    fetch(`/posts/${this.props.blogPostId}`)
      .then(content => this.setState({ content })); 
  }
}

We can replace it with the following call to useEffect:

useEffect(() => { 
  fetch(`/posts/${props.blogPostId}`)
    .then(content => setContent(content));
}, [props.blogPostId]);
Resources