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;