useEffect in React
What is useEffect? useEffect is a React Hook that runs code after a component renders. Some common use cases are: Fetching data from an API Updating the document title Working with localStorage Setting up timers Add
What is useEffect?
useEffect is a React Hook that runs code after a component renders.
Some common use cases are:
- Fetching data from an API
- Updating the document title
- Working with localStorage
- Setting up timers
- Adding event listeners
Syntax
import { useEffect } from "react";
useEffect(() => {
// Code
}, []);
- The first argument is a function containing the code we want to execute.
- The second argument is called the dependency array.
useEffect with an Empty Dependency Array
import { useEffect } from "react";
function App() {
useEffect(() => {
console.log("Component with Empty Dependency Array");
}, []);
return <h1>Hello React</h1>;
}
Output
Component with Empty Dependency Array
This effect runs only once when the component is first rendered.
useEffect with Dependencies
import { useState, useEffect } from "react";
function App() {
const [count, setCount] = useState(0);
useEffect(() => {
console.log("Count Changed");
}, [count]);
return (
<button onClick={() => setCount(count + 1)}>
{count}
</button>
);
}
Whenever count changes, the effect runs again.
Output
Count Changed
This is useful when we want to perform an action whenever a specific state value changes.
useEffect Without Dependency Array
useEffect(() => {
console.log("Runs After Every Render");
});
Since there is no dependency array, the effect runs after every render.
Be careful when using this because unnecessary executions can affect performance.
Originally published by Dev.to WebDev. Aggregated on AIWithGhost for educational purposes — full credit and traffic to the original publisher.