DEV Community

Cover image for My React Journey: Day 26
Ayoola Damilare
Ayoola Damilare

Posted on

My React Journey: Day 26

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");
}, []);
Enter fullscreen mode Exit fullscreen mode

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]);
Enter fullscreen mode Exit fullscreen mode

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!");
  };
}, []);

Enter fullscreen mode Exit fullscreen mode

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>
);
Enter fullscreen mode Exit fullscreen mode

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>;
Enter fullscreen mode Exit fullscreen mode

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>;
Enter fullscreen mode Exit fullscreen mode

This keeps getting better day-by-day

Top comments (0)