What is useEffect hook in react
Posted 3 years ago by Ryan Dhungel
Category: React Hooks
Viewed 1643 times
Estimated read time: 2 minutes
- useEffect accepts two arguments, a function and a dependency array
- Runs only when component mounts on the DOM (component is rendered on the screen) by default
- First argument function can contain effectful code such as fetching posts from server and making available in the state
- Second argument array can be empty or some values
- Leave it empty if you want to run useEffect when component mounts and unmounts (default behaviour)
- 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(() => {
fetchTodosFromServer();
}, [action]);
return (
<div>
<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>
))}
</div>
);
};
export default App;