React Lifecycle Methods: What They Are and How They Work
lifecycle methods are special functions that run at specific times during a component's life, like when it appears or disappears on the screen. With modern React, these are handled using hooks such as useEffect in functional components to manage side effects and updates.How It Works
Think of a React component like a living creature that goes through different stages: birth, life, and death. Lifecycle methods are like checkpoints where you can run code when the component is born (mounted), updated, or about to leave (unmounted).
In older React class components, these were special methods like componentDidMount or componentWillUnmount. Today, with functional components, React uses hooks like useEffect to let you run code at these key moments. This helps you do things like fetch data when the component appears or clean up timers when it disappears.
Example
useEffect to log messages when the component mounts and unmounts.import React, { useEffect } from 'react'; function Timer() { useEffect(() => { console.log('Timer mounted'); const interval = setInterval(() => { console.log('Tick'); }, 1000); return () => { clearInterval(interval); console.log('Timer unmounted'); }; }, []); return <div>Check the console for timer ticks.</div>; } export default Timer;
When to Use
Use lifecycle methods or hooks when you need to run code at specific times in a component's life. For example:
- Fetching data from a server when the component appears.
- Setting up subscriptions or timers.
- Cleaning up resources like timers or event listeners when the component disappears.
- Updating the document title or other side effects after rendering.
These help keep your app efficient and avoid bugs like memory leaks.
Key Points
- Lifecycle methods run at specific stages: mount, update, unmount.
- Modern React uses the
useEffecthook instead of class lifecycle methods. - Always clean up side effects to avoid issues.
- They help manage side effects like data fetching and timers.