Learn

Before we get into creating custom hooks, let’s review what we know about the useEffect() hook.

The useEffect() hook allows developers to perform an action after rendering. These actions are typically side effects of the component rendering and are often reactions to state changes. A common example of one of these “side effects” is fetching data after the component renders.

Remember, useEffect() accepts two arguments:

  1. A callback function which is executed after the component renders
  2. A dependency array which determines how often the effect is executed
useEffect(() => { fetchData('someapi.com/key/123'); }, []); // ← An empty dependency array

When we pass an empty dependency array as the second argument to our effect hook, the callback will only be executed after the component’s first render. In this example, we only want to fetch data once after the first render.

When variables are provided in the dependency array, React will only execute the callback passed to useEffect() when those variables are updated.

const [searchQuery, setSearchQuery] = useState(''); useEffect(() => { fetchData(`someapi.com/search?q=${searchQuery}`); }, [searchQuery]); // ← A single dependency

In this example, we’ll fetch new data only when the searchQuery value changes. In this way, the dependency array allows us to achieve the right balance between making too many API calls and serving the most up-to-date data with our users.

Instructions

1.

In Counter.js, we’ve added a button that allows the user to increment the count and an effect that will change the background if the count is prime! However, it’s not working properly because we haven’t set up our useEffect() hook properly!

Update the dependency array for the useEffect() call such that the effect runs each time the counter value changes.

Then, click the “Click Me” button and see the effect run as the component re-renders! The first few prime numbers are: 2, 3, 5, 7, 11, 13, 17, 19…

Sign up to start coding

Mini Info Outline Icon
By signing up for Codecademy, you agree to Codecademy's Terms of Service & Privacy Policy.

Or sign up using:

Already have an account?