React useEffect Hook
useEffect Hook
What is useEffect ?
useEffect is a React Hook that lets you run code after the component renders.
Ex: Whenever something changes (like state or props), I want to do something (like fetch data, update title, etc.)
- The function runs after the component renders.
- The array [dependencies] controls when the effect should run.
Run on Every Render
Run Only Once (on Mount)
- Pass an empty array [] to run the effect only once, like componentDidMount.
Fetch API Data on Mount
Run on Specific State Change
- Only runs when count changes.
Clean Up Example (like componentWillUnmount)
- return function is the cleanup, useful for timers, listeners, etc.
Type of Dependency | When it Runs |
---|---|
[] (empty array) | Once, on mount |
[value] | When value changes |
(No array) | On every render |
Project: Live Crypto Price Tracker
This project will:
- Use useEffect to fetch live cryptocurrency prices
- Show them in a clean UI
- Refresh automatically every 30 seconds
Tech Stack:
- React (JS)
- useEffect and useState hooks
- Fetch API
CryptoTracker.jsx
- useEffect to fetch data on mount
- Automatic refresh with setInterval
- Cleanup with return function in useEffect
- Conditional rendering (loading vs data)