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
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 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
React onMouseEnter Event React onMouseEnter() is an event handler that triggers when the mouse cursor enters the boundaries of an element. It is particularly useful where you want to initiate actions or display information when the user's cursor hovers over an element. It is similar to the HTML DOM onmouseenter event but us
2 min read
React onBlur Event In React, handling user interactions efficiently is important for building responsive and dynamic applications. One of the commonly used events for managing focus behaviour is the onBlur event. This event is important for tracking when a user moves the focus away from an element, such as an input fi
6 min read
React Events In React, events are actions that occur within an application, such as clicking a button, typing in a text field, or moving the mouse. React provides an efficient way to handle these actions using its event system. Event handlers like onClick, onChange, and onSubmit are used to capture and respond t
8 min read
Effect Management with useEffect Hook in React useEffect serves as a foundational tool in React development, enabling developers to orchestrate side effects within functional components systematically. It facilitates the management of asynchronous tasks, such as data fetching and DOM manipulation, enhancing code organization and maintainability.
3 min read
React onClick Event The onClick event in React is used for handling a function when an element, such as a button, div, or any clickable element, is clicked.SyntaxonClick={handleClick}ParameterThe callback function handleClick which is invoked when onClick event is triggeredReturn TypeIt is an event object containing in
3 min read
React onTouchEnd Event React onTouchEnd event event fires when the user touches screen and releases the touch. Similar to other elements in it, we have to pass a function for process execution.It is similar to the HTML DOM ontouchend event but uses the camelCase convention in React.Syntax:onTouchEnd={function}Parameter :
2 min read