Lifecycle Methods & Conditional Rendering
Today marks another step in my React learning journey, and itβs all about Lifecycle Methods and Conditional Rendering. Understanding how React components are born, grow, and eventually leave the DOM has been a game-changer for me. Add to that the ability to conditionally display content based on user interactions, and suddenly, building dynamic, user-friendly apps feels so sweet!
Lifecycle Methods in React Functional Components
Lifecycle has 3 steps:
1.Initial Step (Mounting Phase):
- Happens when the component renders for the first time.
- useEffect with an empty dependency array ([]) runs only during this phase. Example:
useEffect(() => {
console.log("Component mounted");
}, []);
2.Update Step:
- Triggered when state or props change.
- React re-runs your function component, re-computing states and passing updated props.
- Use useEffect with specific dependencies to handle changes:
useEffect(() => {
console.log("State or props updated!");
}, [dependency1, dependency2]);
3. Exit / Unmounting Phase:
- Happens when the component is removed from the DOM.
- Cleanup code can be added in the return function of useEffect to release memory. Example:
useEffect(() => {
const handleResize = () => console.log("Resized!");
window.addEventListener("resize", handleResize);
return () => {
window.removeEventListener("resize", handleResize);
console.log("Component unmounted, cleanup done!");
};
}, []);
Conditional Rendering
This technique is essential for dynamically rendering components or elements based on conditions.
Ternary Operator
UserGreetings example:
return props.isLoggedIn ? (
<h2 className='welcome-message'>Welcome {props.username}</h2>
) : (
<h2 className='login-prompt'>Please log in to continue</h2>
);
Short-Circuit Evaluation
For simpler conditions, you can use && to render components only when a condition is true:
return props.isLoggedIn && <h2>Welcome, {props.username}</h2>;
Inline Conditional Styles
You can also dynamically style components:
const messageStyle = props.isLoggedIn
? { color: "green" }
: { color: "red" };
return <h2 style={messageStyle}>Welcome, {props.username}</h2>;
This keeps getting better day-by-day
Top comments (0)