What is useEffect hook in ReactJS ?

What is useEffect hook in ReactJS ?

This is the second article on React hook beginner series. If you haven't read the previous article, you can find it here:

useState hook in react

Hooks are a new addition in React 16.8 . They let you use state and other React features without writing a class which are often difficult to use and understand . Now lets see what useEffect actually is .

useEffect Hook

giphy.gif

useEffect hook is part of the react hooks API.

useEffect runs the function on every render of the component.

In React functional components usually, we use useEffect in order to perform side effects like fetching data from an API, directly updating the DOM, and timers .

useEffect accepts two arguments.

The first argument is a function and second one is the dependency .

Let's see an example to demonstrate how to use useEffect :

import { useEffect, useState } from 'react';

function App() {
   const [name,setName] = useState('David');
  const [age,setAge] = useState(20);
  useEffect(()=>{
   console.log('useEffect running');
  });

  return (
    <div className="App">
     <h1>UseEffect Demo</h1>
    <button onClick={()=>setName('Robert')}>Change Name</button>
    {name}
    <button onClick={()=>setAge(30)}>Change Age</button>
    {age}
    </div>
  );
}

export default App;

useEffect runs on every render. Which means it runs once initially when the component first loads and then after, every time the data changes. In this example it logs to the console when the component first loads, then on clicking Change Name button and then on clicking Change Age button .

There are several ways to control when side effects run.We should always include the second parameter which accepts an array. We can optionally pass dependencies to useEffect in this array. Dependency array is a second argument to useEffect to control where this function runs.

Empty dependency array makes sure that the useEffect hook runs the function only once after the first initial render. Then after if the state changes it won't run the function again like the one in the example below :

import { useEffect, useState } from 'react';

function App() {
  const [name,setName] = useState('Nick');
  const [age,setAge] = useState(20);
  useEffect(()=>{
   console.log('useEffect running');
  },[]);

  return (
    <div className="App">
     <h1>UseEffect Demo</h1>
    <button onClick={()=>setName('Jennifer')}>Change Name</button>
    {name}
    <button onClick={()=>setAge(30)}>Change Age</button>
    {age}
    </div>
  );
}

export default App;

Dependencies can either be state or prop values. Now let us see another example where we pass name of state as a dependency .

import { useEffect, useState } from 'react';

function App() {
  const [name,setName] = useState('Nick');
  const [age,setAge] = useState(20);
  useEffect(()=>{
   console.log('useEffect running');
  },[name]);

  return (
    <div className="App">
     <h1>UseEffect Demo</h1>
    <button onClick={()=>setName('Jennifer')}>Change Name</button>
    {name}
    <button onClick={()=>setAge(30)}>Change Age</button>
    {age}
    </div>
  );
}

export default App;

In the example above we have passed the state name as a dependency. Now if we check the console, the effect runs twice: once on the initial render and then when the state name changes . Remember, it won't run the effect when the state age changes because we have not passed age as the dependency array .

Now, let's see an example of fetching data from an external API using useEffect . Here, we will be using fetch API to fetch data from the external API. Also, we will be using JSON Placeholder for testing the endpoint, which is a free fake REST API . Details about the API can be found here .

import { useEffect, useState } from 'react';

function App() {

  const [data, setData] = useState([]);
  useEffect(()=>{
    fetch(`https://jsonplaceholder.typicode.com/posts`)
    .then(response => response.json())
    .then(json => setData(json))
  });

  return (
    <div className="App">
     <ul>
      {data.map(post => (
        <li key={post.id}>
         {post.title}
        </li>
      ))}
    </ul>
    </div>
  );
}

export default App;

After you execute the above code you will see it displays lists of 100 posts in the browser .

To conclude

  • useEffect is a special part of React hooks API which runs on every render.

  • we use useEffect in order to perform side effects like fetching data from an API.

  • useEffect accepts two arguments. The first one is a function and second one is the dependency .

  • dependencies can either be state or prop values.

That was about useEffect hook in React. If you liked the blog post, check out my Twitter where I post daily content related to Web development .

Thanks for reading . Happy Coding !

giphy (1).gif