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:
OutputuseLayoutEffect 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:
OutputuseInsertionEffect 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:
Output
Similar Reads
Built-in React Hooks
In React, built-in Hooks are like tools that empower your components with various functionalities. They give you the flexibility to use different features without having to create class components. You can either utilize the hooks provided by React or mix and match them to create custom hooks tailor
5 min read
New Hooks in React 18
React's state, representing dynamic component data, is integral for effective component management. Initially confined to class components and managed using this.setState, the introduction of React Hooks in version 16.8 extended state usage to functional components. Hooks, functions enabling state a
5 min read
npm react hook form
react-hook-form is a powerful library that simplifies the process of building and managing forms in React applications. It provides a minimal API, which allows for easy integration and better performance. With react-hook-form, we can validate form inputs, handle errors, and control form state effici
4 min read
Tilt effect in ReactJS
Creating a tilt effect in React JS typically involves applying styles dynamically based on user interaction, such as mouse movements. This tilt effect can enhance the UI of our web application so that it seems more realistic and better. We will do this using the Tilt Component from the "react-parall
3 min read
React Hooks
ReactJS Hooks are one of the most powerful features of React, introduced in version 16.8. They allow developers to use state and other React features without writing a class component. Hooks simplify the code, make it more readable, and offer a more functional approach to React development. With hoo
10 min read
State Hooks in React
State Hooks, introduced in React 16.8, revolutionized how developers manage state in functional components. Before State Hooks, state management was primarily confined to class components using the setState method. State Hooks, such as useState, enable functional components to manage local state eff
3 min read
React onFocus event
The onFocus event in React is triggered when an element receives focus, meaning it becomes the active element that can accept user input. This event is commonly used to execute functions or perform actions when an element gains focus. It is similar to the HTML DOM onfocus event but uses the camelCas
2 min read
React onInput Event
React onInput is an event handler that triggers then there is any change in the input field. It is fired immediately when the user is changing input. It is one of the form events that updates when the input field is modified. It is similar to the HTML DOM oninput event but uses the camelCase convent
2 min read
React onMouseDown Event
The onMouseDown event is a native DOM event in React that triggers when the mouse button is pressed down on an element. It is part of a set of mouse events that React and the DOM handle, which includes events like onClick, onMouseUp, onMouseEnter, and others.onMouseDown occurs when any mouse button
5 min read
How To Create a Custom Hook in React?
In web application development, developers often need to reuse logic multiple times, which can become difficult to manage manually. So, the custom hook can be used to solve the problem of reusing complex stateful logic across multiple components.What are Custom Hooks?Custom Hooks are special functio
4 min read