DEV Community


React Hooks: useEffect

I've been tinkering with computers since I was a teen. I'm currently pivoting from my current role as Tech Support manager to Full Stack Web Developer. I'm actively seeking employment in the field.
・2 min read

useEffect allows you to fire side effects in functional components.

It acts much like componentDidMount, but it will fire any time the component re-renders unless you pass in a secondary parameter – an array. This array can have any (or no) value, but generally you would link it to whatever property you are trying to update or keep track of with useEffect. If the array is empty, it will act very much like componentDidMount and only fire once when the component is first rendered, and not on subsequent re-renders.

In the example below, the useEffect is fetching some data to display on the frontend to the user. Normally one would probably want to use an async/await to do this, but there are some caveats when doing this with useEffect.

Async actually returns an ‘asyncFunc’ object, which useEffect does not want. So if you want to write an asynchronous function inside useEffect, you would want to declare the async as a named function inside the body of useEffect.

Another caveat is that if you want to use a conditional, it must be placed inside of the useEffect function. You cannot place the useEffect function inside of a conditional. See the code below.

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

import Card from '../card/card.component';

// in this example we are getting data from an API and displaying it to the user, who can type a query into a search field
const UseEffectExample = () => {
  if (searchQuery.length > 0) {
    //set the initial values
    const [user, setUser] = useState(null);
    const [searchQuery, setSearchQuery] = useState('');

    useEffect(() => {
      const fetchFunc = async () => {
        const response = await fetch(`${searchQuery}`);

        // convert the response to JSON     
        const resJson = await response.json();

        // in this case, the response is a an array, so using resJson[0] will return the first item of any response (or undefined/null if none)


    }, [searchQuery]); // place the property inside the array so that whenever the search query changes, call useEffect again

  return (
  // your UI code here    

Discussion (0)