useEffect can impact your app’s performance, so it's important to use it wisely. Let's break down why and clarify some key concepts in React.js.
Initial Render vs Re-render
Initial render: This happens the first time a component is rendered to the DOM, typically when the app loads or the root component is mounted.
Re-render: This occurs when the component’s state or props change, prompting React to update the DOM accordingly. It uses a virtual DOM to optimize updates and apply only the necessary changes.
Example Code:
import { useState, useEffect } from 'react';
const App = () => {
const [toggle, setToggle] = useState(false);
return (
<>
<h2>useEffect cleanup function</h2>
<button className="btn" onClick={() => setToggle(!toggle)}>
Toggle component
</button>
{toggle && <AnotherComponent />}
</>
);
};
const AnotherComponent = () => {
useEffect(() => {
console.log('mounting - another component');
}, []);
return <h2>Another Component</h2>;
};
Clicking the button toggles AnotherComponent, triggering multiple mounts (initial renders).
Performance Concerns
This setup can cause performance issues, especially with things like:
Timers (setInterval): Equivalent to subscribing to an event.
Event listeners: Another source of potential performance problems.
These issues arise because the side effects (e.g., timers, event listeners) aren't properly cleaned up, leading to memory leaks or unnecessary work.
Solution: useEffect Cleanup Function
To address these issues, use the useEffect cleanup function. This ensures that any side effects are properly reversed when the component unmounts or when dependencies change.
Simple Example:
useEffect(() => {
// Effect code, like adding a timer or event listener.
return () => {
// Cleanup code, like clearing the timer or removing the event listener.
};
}, []);
This guarantees that side effects are cleaned up when the component unmounts, improving performance.
Also, when using useEffect, you might want to check out this helpful article: You might not need an effect. It can help you decide if useEffect is truly necessary in certain scenarios.
Credits: John Smilga’s React course.
