The useEffect hook runs side effects after a render, with the frequency controlled by its dependency array. It takes two arguments in the form useEffect(callback, dependencies). The callback contains the side‑effect logic and runs after the initial render and again whenever one of the dependencies changes (or after every render if you omit the dependency array).
import React, { useState, useEffect } from 'react';function TitleCount() {const [count, setCount] = useState(0);useEffect(() => {document.title = `You clicked ${count} times`;}, [count]);return <button onClick={() => setCount(prev => prev + 1)}>+</button>;}
There are two main rules to keep in mind when using hooks:
Common mistakes to avoid are calling hooks inside of loops, conditions, or nested functions.
// Instead of confusing React with code like this:if (userName !== '') {useEffect(() => {localStorage.setItem('savedUserName', userName);});}// We can accomplish the same goal, while consistently calling our hook every time:useEffect(() => {if (userName !== '') {localStorage.setItem('savedUserName', userName);}});
Effect hooksEffect hooks are useful for performing “side effects” after render such as fetching data and reacting to state changes.
useEffect(() => {fetch("https://some-api.com/get-some-user-information").then(response => {console.log(response)}).catch(error => {console.log(error)});}, [])
The dependency array is used to tell the useEffect() method when to call the effect.
useEffect(() => {alert('called after every render');});useEffect(() => {alert('called after first render');}, []);useEffect(() => {alert('called when value of `endpoint` or `id` changes');}, [endpoint, id]);
Custom Hooks are JavaScript functions that make use of other hooks, follow the rules of hooks, and whose names begin with use. Custom hooks are simply a convention and the programmer can decide what they do and what they return.
The provided example is from the Playing Hooky project. This custom hook changes the page’s appearance to “dark” or “light” mode while providing the current theme value for use elsewhere in the application.
const useTheme = () => {// "theme" state with a default value of "light".const [theme, setTheme] = useState("light");// Changes the pages CSS styling.useEffect(() => {document.documentElement.setAttribute("data-theme", theme);}, [theme]);// Function executed in the application.const onToggleTheme = () => {setTheme((previousTheme) => previousTheme === "light" ? "dark" : "light");};// Makes the function available for use in the application.return {theme, onToggleTheme};}
Custom hooks have many benefits. They: