Skip to main content
X

Explore your training options in 10 minutes

JavaScript Tutorials

How to Use React useEffect

Ryan Manchester - February 09, 2021


The development team at React introduced the concept of Hooks in React version 16.8. A React Hook allows the use of state and other React features in a function component. With the hook useState, a function component can set its own internal state without having to be rewritten as a class component.

Check out this guide to review the differences in React class and functional components.

Another widely used Hook in React is useEffect. With useEffect, side effects (or “effects”) are performed from the context of a functional component. Remember that side effects occur in JavaScript functions as well.

Get offers and scholarships from top coding schools illustration

Find Your Bootcamp Match

  • Career Karma matches you with top tech bootcamps
  • Access exclusive scholarships and prep courses










By continuing you agree to our Terms of Service and Privacy Policy , and you consent to receive offers and opportunities from Career Karma by telephone, text message, and email.

Side effects occur when a function changes something outside of its body. In React, it’s the same thing and can include data fetching, subscriptions, or change the DOM from React components before.

What is useEffect?

The React Hook useEffect allows a functional component to perform side effects. It works in a similar fashion to the lifecycle methods componentDidMount, componentWillUpdate, and componentWillUnmount in React class components. Refer to this introduction on React lifecycle methods for more details.

In this article, we will see a basic example of how to start using Hooks. The intention of this article is to serve as an introduction, not a deep dive. For a comprehensive look at useEffect, read this overview once you are familiarized with React Hooks.

React Hooks Syntax

To understand useEffect, we first need to briefly go over the syntax for the useState Hook. When using Hooks, they must be imported just as React is imported.

import React, { useState, useEffect } from 'react';

Now we can define our functional component with our Hooks inside. This is making use of JavaScript function scope. When we define our useEffect Hook inside of the functional component, it has access to state and props through scope. For more on scope, review with this primer .

useState syntax

For the sake of clarity, let’s use a simple counter for our example. We will output to the DOM how many times a button is clicked. Our functional component complete with imports will look like this:

import React, {useState, useEffect} from 'react'
import ReactDOM from 'react-dom'

  const ButtonCounter = () => {
    return (
      <button>Click Me</button>
    )
  }
    


ReactDOM.render(
  <ButtonCounter />,
  document.getElementById('container')
);

This renders our button to the DOM. Before we define useEffect, we can set our initial state by defining the useState Hook.

const [count, setCount] = useState(0);

By using this syntax, React sets the first variable to the initial state. In this case, the variable “count” is set by the argument passed to useState. React has set our initial state of count to 0. The second variable will be used as a function to update the count.

Now that we’ve set an initial state of count to 0, we can use our setCount function to update the state.

const ButtonCounter = () => {
  const [count, setCount] = useState(0);
  return (
    <div>
      <p>You clicked the button {count} times</p>
      <button onClick={() => setCount(count + 1)}>Click Me</button>
      </div>
  )
}

By using our setCount as a callback function to our onClick property, we can update the DOM every time the button is clicked.

This means our setCount function as defined when setting our initial state with useState is working! Now that we’ve seen the syntax for the useState Hook, let’s look at useEffect.

Venus, a software engineer at Rockbot

"Career Karma entered my life when I needed it most and quickly helped me match with a bootcamp. Two months after graduating, I found my dream job that aligned with my values and goals in life!"

Venus, Software Engineer at Rockbot

useEffect Syntax

As stated earlier, useEffect defines the use of side effects. Changes to components through data fetching and manual DOM changes constitute side effects. The useEffect Hook is called every time the component renders.

It works similarly to componentDidMount and componentDidUpdate in React class components. Going forward with our counter example, we will have useEffect update our DOM by displaying a name in our <p> element.

const [count, setCount] = useState(0);
  const [name, setName] = useState(" ");

  useEffect(() => {
    setName(name + "Ryan")
  })
  return (
    <div>
      <p>Hello {name}! You clicked {count} times</p>
      <button onClick={() => setCount(count + 1)}>Click Me</button>
      </div>
  )
}

This is intentionally coded incorrectly. What gets pushed to the DOM proves useEffect is called with each render of the component.

This is occurring because by default, the useEffect Hook behaves like a combination of componentDidMount and componentWillUpdate.

In order to customize our Hook to render only when the component mounts, we can send a second argument to useEffect. By passing useEffect an empty array ([]) as the second argument, React knows to only call useEffect when the component mounts.

useEffect(() => {
    setName(name + "Ryan")
  }, [])

Now, we should see the string “Ryan” displayed only once our functional component mounts.

Great! Getting used to using Hooks will take some time. With that in mind, the official React documentation has an updated guide on using Hooks. Read it here .

Conclusion

In this introduction to the React useEffect Hook, we learned what Hooks are and how to use them. We also covered the syntax for the useState and useEffect Hooks with an elementary example for each.

The potential uses for Hooks goes far beyond what is covered in this primer. After reading this and spending some time in your own code, branch out to the linked resources to deepen your grasp on React Hooks. Although class components aren’t going anywhere, Hooks are the future of React, so stay informed and up to date on them!

About us: Career Karma is a platform designed to help job seekers find, research, and connect with job training programs to advance their careers. Learn about the CK publication.

What's Next?

Ryan Manchester

About the author: Ryan is a technical writer at Career Karma, where he covers programming languages, technology, and web development. The Texas native earned his Bachelor's of Music Composition from the University of North Texas. Ryan is currently pursuing further education in web development, aiming to graduate from Flatiron School with a certification in full stack web development. Since joining the Career Karma team in November 2020, Ryan has used his expertise to cover topics like React and Ruby on Rails.

Skip to main content