Open In App

Effect Hooks in React

Last Updated : 20 Feb, 2024
Improve
Improve
Like Article
Like
Save
Share
Report

Effect Hooks in React allow components to interact with and stay synchronized with external systems, such as handling network requests, manipulating the browser’s DOM, managing animations, integrating with widgets from other UI libraries, and working with non-React code. Essentially, effects help components communicate and coordinate with the world outside of React.

  • useEffect is used to connect components to an external system.
  • useLayoutEffect performs a side effect immediately after the browser has painted the screen.
  • useInsertionEffect is used before ReactJS makes changes to the DOM, and in this libraries can insert the dynamic CSS.

We will discuss about the following types of Effect Hooks in React.

Steps to Create React Application:

Step 1: Create a react project folder, open the terminal, and write the following command.

npm create-react-app project
cd project

Step 2: Install the required dependencies.

npm i react-bootstrap bootstrap

useEffect Hooks:

The useEffect hook in React is a powerful tool for managing tasks like fetching data from a server or updating the user interface. It’s like having a reliable assistant that takes care of all the behind-the-scenes work in your functional components. By default, useEffect kicks in after every render, making sure everything stays up to date.

  • Runs After Render: useEffect lets you perform side effects in your components after every render. These effects might include data fetching, setting up subscriptions, or manually changing the DOM.
  • Runs Once by Default: By default, the effect function passed to useEffect runs after the first render and after every update. This is similar to the lifecycle methods componentDidMount, componentDidUpdate, and componentWillUnmount in class components.
  • Dependency Array: You can also provide a dependency array as the second argument to useEffect. This array specifies values that the effect depends on. If any of these values change between renders, the effect will run again. If the array is empty, the effect only runs once after the initial render.
  • Cleanup Function: useEffect can optionally return a cleanup function. This function runs before the effect is re-executed (before every update) and when the component is unmounted. It’s used to clean up any resources or subscriptions created by the effect to prevent memory leaks.

Syntax:

useEffect(<FUNCTION>, <DEPENDECY>)

Example: Below is an example of useEffect Hooks.

Javascript




// App.js
import {
    useState,
    useEffect
} from "react";
 
function App() {
    const [count, setCount] = useState(0);
 
    useEffect(() => {
        document.title = `You clicked ${count} times`;
    }, [count]);
 
    return (
        <div>
            <button onClick={() =>
                setCount((prevCount) =>
                    prevCount + 1)}>
                Click {count} times{" "}
            </button>
        </div>
    );
}
export default App;


Output:

gfg49

Output

useLayoutEffect Hooks:

The useLayoutEffect hook in React is a tool that allows you to perform side effects synchronously after the DOM has been updated but before the browser has repainted the screen.

  • Synchronous Execution: Unlike useEffect, which runs asynchronously after the browser paints, useLayoutEffect executes synchronously immediately after the DOM has been updated but before the browser has a chance to paint the changes on the screen.
  • Performance Considerations: Since useLayoutEffect runs synchronously, it can potentially cause performance issues, especially if it involves computationally expensive tasks or triggers additional renders. It’s crucial to use useLayoutEffect thoughtfully and consider if useEffect might be a more suitable choice for your specific use case.

Syntax:

useLayoutEffect(setup, dependencies)
or
useLayoutEffect(()=> // some code to execute , dependency //e.g. [] if none)

Example: Below is an example of useLayoutEffect Hooks.

Javascript




// App.js
import React, {
    useLayoutEffect,
    useState
} from "react";
 
const App = () => {
    const [value, setValue] = useState("GFG");
 
    useLayoutEffect(() => {
        console.log(
            "UseLayoutEffect is called with the value of ",
            value
        );
    }, [value]);
    setTimeout(() => {
        setValue("GeeksForGeeks");
    }, 2000);
 
    return (
        <div
            style={{
                textAlign: "center",
                margin: "auto",
            }}
        >
            <h1 style={{ color: "green" }}>{value}</h1>
            is the greatest portal for geeks!
        </div>
    );
};
 
export default App;


Output:

gfg51

Output

useInsertionEffect Hooks:

The useInsertionEffect Hook in React 18 is designed to insert elements such as dynamic styles into the DOM before the layout effects are triggered. This hook is particularly useful for client-side operations where pre-layout element insertion is crucial.

  • Triggering on DOM Insertion: Similar to how useEffect triggers after a component has been mounted or updated, useInsertionEffect might trigger when a specific element is inserted into the DOM for the first time.
  • Handling Cleanup: Just like useEffect, useInsertionEffect might also support cleanup functionality to remove any event listeners or clean up resources when the component or element is unmounted or removed from the DOM.

Syntax:

useInsertionEffect(setup, dependencies?)

Example: Below is an example of useInsertionEffect Hooks.

Javascript




//App.js
import React, { useState } from 'react';
import { useInsertionEffect } from 'react';
const App = () => {
    const [dyna_color, set_Dyna_Color] = useState('green');
    const dStyle = `
    .dynamic-element {
    color: ${dyna_color};
    transition: color 0.5s ease;
    }
`;
    useInsertionEffect(() => {
        const styleEle = document.createElement('style');
        styleEle.innerHTML = dStyle;
        document.head.appendChild(styleEle);
        return () => {
            document.head.removeChild(styleEle);
        };
    }, [dyna_color]);
    const btnFn = () => {
        set_Dyna_Color('red');
    };
    return (
        <div className="dynamic-element">
            <h1>Hello, GeeksforGeeks!</h1>
            <h3>useInsertionEffect Hook - Example 1</h3>
            <button onClick={btnFn}>Change Color</button>
        </div>
    );
}
export default App;


Output:

gfg52

Output



Like Article
Suggest improvement
Share your thoughts in the comments

Similar Reads