What is useEffect hook in react

Posted 4 years ago by Ryan Dhungel

Category: React Hooks

Viewed 2033 times

Estimated read time: 2 minutes

  1. useEffect accepts two arguments, a function and a dependency array
  2. Runs only when component mounts on the DOM (component is rendered on the screen) by default
  3. First argument function can contain effectful code such as fetching posts from server and making available in the state
  4. Second argument array can be empty or some values
  5. Leave it empty if you want to run useEffect when component mounts and unmounts (default behaviour)
  6. If you want to run useEffect when certain values change, you can pass those values as dependencies in this array

Here is an example of using useEffect hook to fetch a list of todos from remove server. This example also shows how you can pass dependency array to controll when to run useEffect.


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

const App = () => {
  const [todos, setTodos] = useState([]);
  const [action, setAction] = useState(false);

  const fetchTodosFromServer = async () => {
    const response = await fetch("https://jsonplaceholder.typicode.com/todos");
    const todos = await response.json();
    setTodos(prevState => [...prevState, ...todos]);

  useEffect(() => {
  }, [action]);

  return (
      <button onClick={() => setAction(!action)}>Refetch todos</button>
      <hr />
      <p>Total todos: {todos.length}</p>
      <hr />
      {todos.map(todo => (
        <p key={todo.id}>{todo.title}</p>

export default App;