useEffect in React
Expert-Level Explanation
In React 18, theuseEffect
hook is a fundamental tool that handles side effects in functional components. It replaces the lifecycle methods found in class components, namely componentDidMount
, componentDidUpdate
, and componentWillUnmount
. TheuseEffect
hook runs after every completed render by default, but it can be configured to run only when certain values have changed (during an update) or once the component mounts. Additionally, it can return a function to perform cleanup operations, similar tocomponentWillUnmount
.
Creative Explanation
Imagine your React component as a stage actor in a play. When the actor first comes on stage (mounts), they need to prepare (initial useEffect
execution). As the play goes on and the script changes (updating), the actor adapts their performance (subsequent useEffect
executions). Finally, when their part is over, they need to clean up and leave the stage (unmounting, where useEffect
cleanup runs).
Practical Explanation with Code
import React, { useState, useEffect } from 'react';
function MyComponent({ prop }) {
const [state, setState] = useState(0);
// Run on mount and every update
useEffect(() => {
console.log('Component updated');
// Cleanup function runs on unmount and before every update
return () => {
console.log('Cleanup before unmount or next update');
};
});
// Run only on mount
useEffect(() => {
console.log('Component mounted');
}, []);
// Run when `prop` changes
useEffect(() => {
console.log('Prop changed');
}, [prop]);
return <button onClick={() => setState(state + 1)}>Increment</button>;
}
Real-World Example
Consider an online chat application. When a user enters a chat room (component mounts), useEffect
connects to the server to fetch chat history. As the user interacts or when new messages arrive (updating), useEffect
may update the chat window may be updated. When the user leaves the chat room (unmounting), useEffect
the cleanup function disconnects from the server and performs any necessary cleanup.