React provides many Hooks that make functional components powerful and easy to manage. One of the most important Hooks is useEffect.
The useEffect Hook is used to perform side effects in React components.
What is a Side Effect?
A side effect is any action that happens outside the normal rendering process of a component.
Examples:
Fetching data from an API
Updating the webpage title
Using timers
Adding event listeners
Syntax of useEffect
useEffect(() => {
}, []);
The first part is a function containing the side effect.
The second part is the dependency array.
Example of useEffect
import { useEffect } from "react";
function App() {
useEffect(() => {
console.log("Component Rendered");
}, []);
return (
<h1>Hello React</h1>
);
}
export default App;
Explanation
The message prints when the component renders for the first time.
The empty dependency array [] means it runs only once.
Dependency Array
The dependency array controls when the effect runs.
Empty Array
useEffect(() => {
console.log("Runs once");
}, []);
Runs only once after the first render.
With Dependency
useEffect(() => {
console.log("Runs when count changes");
}, [count]);
Runs whenever count changes.
Why Use useEffect?
useEffect helps developers:
Handle API calls
Manage timers
Update DOM content
Perform actions after rendering
Top comments (0)