πŸŽ‰ 75% of content is free forever β€” Unlock Premium from $10/mo β†’
CW
Search courses…
πŸ’Ό Servicesℹ️ Aboutβœ‰οΈ ContactView Pricing Plansfrom $10

Component Lifecycle

React Fundamentals🟒 Free Lesson

Advertisement

Component Lifecycle

Mounting, updating, unmounting phases, and useEffect equivalents.

Overview

Understanding lifecycle helps manage side effects and resource cleanup.

Key Concepts

  • Mounting β€” Component appears in the DOM
  • Updating β€” State or props change
  • Unmounting β€” Component is removed from DOM
  • useEffect β€” Combines componentDidMount, componentDidUpdate, componentWillUnmount
  • useLayoutEffect β€” Fires synchronously after DOM mutations

Code Examples

function LifecycleDemo({ userId }) {
  const [user, setUser] = useState(null);

  // componentDidMount + componentDidUpdate(userId)
  useEffect(() => {
    console.log('Component mounted or userId changed');
    fetchUser(userId).then(setUser);
    
    // componentWillUnmount
    return () => {
      console.log('Cleanup: component will unmount or userId changing');
    };
  }, [userId]);

  // componentDidMount only
  useEffect(() => {
    console.log('Runs once on mount');
  }, []);

  // Runs after every render
  useEffect(() => {
    console.log('Runs on every render');
  });

  // useLayoutEffect - runs synchronously after DOM updates
  useLayoutEffect(() => {
    const height = document.body.scrollHeight;
    console.log('Layout effect, body height:', height);
  });

  return <div>{user?.name}</div>;
}

Practice

Convert a class component with lifecycle methods to function components with hooks.

⭐

Premium Content

Component Lifecycle

Unlock this lesson and 900+ advanced tutorials with a Premium plan.

🎯End-to-end Projects
πŸ’ΌInterview Prep
πŸ“œCertificates
🀝Community Access

Already a member? Log in

Need Expert React Help?

Get personalized tutoring, project support, or professional consulting.

Advertisement