HTML tutorial
CSS3 tutorial
Bootstrap tutorial
JavaScript tutorial
JQuery tutorial
AngularJS tutorial
React tutorial
NodeJS tutorial
PHP tutorial
Python tutorial
Python3 tutorial
Django tutorial
Linux tutorial
Docker tutorial
Ruby tutorial
Java tutorial
C tutorial
C ++ tutorial
Perl tutorial
JSP tutorial
Lua tutorial
Scala tutorial
Go tutorial
ASP.NET tutorial
C # tutorial
The useEffect Hook allows you to perform side effects in your components
Some effects require cleanup to reduce memory leaks.
Timeouts, subscriptions, event listeners, and other effects that are no longer needed should be disposed.
We do this by including a return function at the end of the useEffect
Hook.
Clean up the timer at the end of the useEffect
Hook:
import { useState, useEffect } from "react";
import ReactDOM from "react-dom/client";
function Timer() {
const [count, setCount] = useState(0);
useEffect(() => {
let timer = setTimeout(() => {
setCount((count) => count + 1);
}, 1000);
return () => clearTimeout(timer)
}, []);
return <h1>I've rendered {count} times!</h1>;
}
const root = ReactDOM.createRoot(document.getElementById('root'));
root.render(<Timer />);
Note: To clear the timer, we had to name it.
What do you need to add to the second argument of a useEffect
Hook to limit it to running only on the first render?
import { useState, useEffect } from "react"; import ReactDOM from "react-dom/client"; function App() { const [data, setData] = useState([]); useEffect(() => { setData(getData()) }, ); return <DisplayData data={data} />; } const root = ReactDOM.createRoot(document.getElementById('root')); root.render(<App />);