MyInternships.in

Components & Props

React Component Lifecycle

Every component goes through three phases: mounting (added to the DOM), updating (re-rendered because state or props changed) and unmounting (removed). Classes expose these as named methods; function components cover all three with useEffect.


What is Component Lifecycle in React?

Every component goes through three phases: mounting (added to the DOM), updating (re-rendered because state or props changed) and unmounting (removed). Classes expose these as named methods; function components cover all three with useEffect.

Why Component Lifecycle matters

Lifecycle thinking is how you decide where to start a subscription, where to fetch data, and — most importantly — where to clean up so you do not leak timers and listeners.

Component Lifecycle example

The same lifecycle in both styles
JSX
// Class
componentDidMount()    { start(); }
componentDidUpdate(p)  { if (p.id !== this.props.id) refetch(); }
componentWillUnmount() { stop(); }

// Function — one effect covers all three
useEffect(() => {
  start();               // mount, and re-run when id changes
  return () => stop();   // cleanup before re-run and on unmount
}, [id]);

How this works

The dependency array replaces the manual prop comparison in componentDidUpdate, and the returned function replaces componentWillUnmount. One effect expresses what took three methods.

Key points to remember

  • Mount: the component function runs, the DOM is committed, then effects fire.
  • Update: the same sequence, preceded by the previous effect’s cleanup.
  • Unmount: only cleanup functions run.
  • Group effects by concern, not by lifecycle phase — one effect per subscription reads better than one giant effect.

Common mistakes with Component Lifecycle

  • Fetching in the component body instead of an effect, which fires on every render.
  • Omitting cleanup and leaking intervals, event listeners or WebSocket connections.

React Component Lifecycle— Interview Questions & FAQs

What is the useEffect equivalent of componentDidMount?+

useEffect(() => { … }, []) with an empty dependency array runs once after the first render. In StrictMode development it runs, cleans up and runs again to verify your cleanup works.

Related React Topics

Keep learning with these closely related lessons.

Ready to use your React skills?

Find verified React internships and fresher developer jobs across India.

Browse React Internships