🎉 75% of content is free forever — Unlock Premium from $10/mo →
CW
đŸ’ŧ 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.

Need Expert React Help?

Get personalized tutoring, project support, or professional consulting.

Advertisement