π4
π§Ώ ReactJS Cheat-Sheet
This Post includes a ReactJs cheat sheet to make it easy for our followers to work with Reactjs.
π6β€2
The useEffect clean-up callback executes on every render
Most people think it executes only when the component unmounts, but thatβs not true.
On every render, the clean-up callback from the previous render executes just before the next effect execution.
Letβs see an example:
This logs the following:
π Why This Matters?
This behavior is essential for managing subscriptions, event listeners, and cleanup logic effectively.
Adding a dependency array ensures the effect runs only when needed
Most people think it executes only when the component unmounts, but thatβs not true.
On every render, the clean-up callback from the previous render executes just before the next effect execution.
Letβs see an example:
function SomeComponent() {
const [count, setCount] = useState(0)
useEffect(() => {
console.log('The current count is ', count)
return () => {
console.log('The previous count is ', count)
}
})
return <button onClick={() => setCount(count + 1)}>Click me</button>
}
This logs the following:
// Component mounts
The current count is 0
// Click
The previous count is 0
The current count is 1
// Click
The previous count is 1
The current count is 2
// Component unmounts
The previous count is 2
π Why This Matters?
This behavior is essential for managing subscriptions, event listeners, and cleanup logic effectively.
Adding a dependency array ensures the effect runs only when needed
β€βπ₯5π2