Run side effects: timers, subscriptions and fetching.
useEffect runs code after rendering, for things outside React: timers, data fetching, subscriptions, document title.
useEffect(() => { ... return cleanup; }, [dependencies]);
[]: run once after the first render.
[value]: run again whenever value changes.
Return a cleanup function to stop timers or listeners when the component unmounts.
💡 Key Takeaways: React useEffect
Mastering React useEffect helps you write clean and reliable React code. Follow standard conventions, test edge cases, and keep logic simple. Try running the code example below and complete the exercises to build confidence.
React useEffect Code Example
React
<div id="root"></div>
<script src="https://unpkg.com/react@18.3.1/umd/react.development.js"></script>
<script src="https://unpkg.com/react-dom@18.3.1/umd/react-dom.development.js"></script>
<script src="https://unpkg.com/@babel/standalone@7.25.6/babel.min.js"></script>
<script type="text/babel">
const { useState, useEffect, useRef, useMemo, createContext, useContext } = React;
function Clock() {
const [time, setTime] = useState(new Date());
useEffect(() => {
const id = setInterval(() => setTime(new Date()), 1000);
return () => clearInterval(id); // cleanup
}, []);
return <h2>{time.toLocaleTimeString()}</h2>;
}
function App() {
const [show, setShow] = useState(true);
const [clicks, setClicks] = useState(0);
useEffect(() => {
document.title = `Clicked ${clicks} times`;
}, [clicks]);
return (
<div>
<button onClick={() => setShow(!show)}>{show ? "Hide" : "Show"} clock</button>{" "}
<button onClick={() => setClicks(clicks + 1)}>Clicks: {clicks}</button>
{show && <Clock />}
</div>
);
}
ReactDOM.createRoot(document.getElementById("root")).render(<App />);
</script>
Free sign-in required · Google login available
Stuck on something?
Ask the community in the CodesInTech forum.
Need a developer?
Learning on your own is great — and when you need professional help, our team builds custom software, websites and mobile apps for clients worldwide.
Explore Our Services