xxxxxxxxxx
import React, { useEffect, useState } from 'react';
const [count,setCount] = useState(0);
//The effect runs after each render since no dependencies are specified.
//run each render
useEffect(() => {
console.log("no depencies, no test");
})
//The effect runs once after the initial render due to the empty dependency array.
//only run start
useEffect(() => {
console.log("include depencies, no test");
},[])
//The effect runs after the initial render and whenever the count state variable changes.
//run start render and when changing count
useEffect(() => {
console.log("include depencies and test");
},[count])
return(
<div classsName="container">
<h2>{count}</h2>
<button onClick={() => setCount(count + 1)} > click </button>
</div>
xxxxxxxxxx
import React, { useEffect } from 'react';
export const App: React.FC = () => {
useEffect(() => {
}, [/*Here can enter some value to call again the content inside useEffect*/])
return (
<div>Use Effect!</div>
);
}
xxxxxxxxxx
import { useState, useEffect } from 'react';
function App() {
const [pieceOfState, setPieceOfState] = useState(0);
useEffect(() => {
console.log('I\'m in useEffect!');
console.log('This will be called whenever an instance of this component mounts');
console.log('or whenever pieceOfState is updated');
}, [pieceOfState]);
return (
<div>
<button onClick={() => setPieceOfState(pieceOfState + 1)}>Click Me to Update pieceOfState!</button>
</div>
);
}
xxxxxxxxxx
import React, { useState, useEffect } from 'react'
export default function App() {
const [count, setCount] = useState(0)
const color = count % 5 === 0 ? 'red' : 'blue'
useEffect(() => {
document.body.style.backgroundColor = color
}, [color])
return (
<button
onClick={() => {
setCount(count + 1)
}}
>
Click HERE to increment: {count}
</button>
)
}
xxxxxxxxxx
import { useEffect } from 'react';
import { createConnection } from './chat.js';
function ChatRoom({ roomId }) {
const [serverUrl, setServerUrl] = useState('https://localhost:1234');
useEffect(() => {
const connection = createConnection(serverUrl, roomId);
connection.connect();
return () => {
connection.disconnect();
};
}, [serverUrl, roomId]);
// ...
}
xxxxxxxxxx
import {useEffect, useState} from 'react';
export default function App() {
const [counter, setCounter] = useState(0);
// ✅ hook is called at top level (not conditionally)
useEffect(() => {
if (counter > 0) {
console.log('hello world');
}
});
return (
<div>
<button onClick={() => setCounter(counter + 1)}>toggle loading</button>
<h1>Hello world</h1>
</div>
);
}
xxxxxxxxxx
import React, { useState, useEffect } from "react";
const App = () => {
const [color, setColor] = useState("black");
useEffect(() => {
const changeColorOnClick = () => {
if (color === "black") {
setColor("red");
} else {
setColor("black");
}
};
document.addEventListener("click", changeColorOnClick);
return () => {
document.removeEventListener("click", changeColorOnClick);
};
}, [color]);
return (
<div>
<div
id="myDiv"
style={{
color: "white",
width: "100px",
height: "100px",
position: "absolute",
left: "50%",
top: "50%",
backgroundColor: color,
}}
>
This div can change color. Click on me!
</div>
</div>
);
};
export default App;
xxxxxxxxxx
import React, { useState, useEffect } from 'react';
function Example() {
const [count, setCount] = useState(0);
// Similar to componentDidMount and componentDidUpdate:
useEffect(() => {
// Update the document title using the browser API
document.title = `You clicked ${count} times`;
});
return (
<div>
<p>You clicked {count} times</p>
<button onClick={() => setCount(count + 1)}>
Click me
</button>
</div>
);
}
Source:reactjs.org
3
React useEffect, useState
xxxxxxxxxx
import { useState, useEffect } from "react";
import ReactDOM from "react-dom/client";
function Timer() {
const [count, setCount] = useState(0);
useEffect(() => {
setTimeout(() => {
setCount((count) => count + 1);
}, 1000);
});
return <h1>I've rendered {count} times!</h1>;
}
const root = ReactDOM.createRoot(document.getElementById('root'));
root.render(<Timer />);
xxxxxxxxxx
most common cases how useEffect implementation:
- fetch data from API,
- directly updating the DOM,
- use timers and real-time data displays (such as BTC current price)
- validating input field
- trigger animation on new array value
-
// 1- EVERY RERENDER
useEffect( () => {
console.log("It runs everytime this component rerenders")
});
// 2- ON MOUNT
useEffect( () => {
console.log("It Only runs once (When the component gets mounted)")
}, []);
// 3- DEPENDING ON CONDITION
useEffect( () => {
console.log("It runs everytime the condition is changed")
}, [condition]); //basically the dependency array determines when the rerender happens
// 4- DEPENDING ON CONDITION, BUT WITH "clean up"
useEffect( () => {
console.log("It runs everytime my condition is changed")
return () => {
console.log("Use this return as a 'clean up tool' (it runs before the actual code)")
}
}, [condition]);