Overview of State and Lifecycle in React
1. Understanding State in React
State is a fundamental concept in React that allows components to manage and respond to data changes over time. Unlike props, which are passed down from parent to child components, state is local to the component and can be modified internally. The ability to manage state is crucial for building dynamic and interactive user interfaces.
2. Key Characteristics of State
3. Using State
In functional components, the useState
hook is commonly used to manage state. It returns an array with the current state value and a function to update it.
4. Updated Timer Component Using State
import React, { useState, useEffect } from 'react';
function Timer() {
// State to hold the number of seconds
const [seconds, setSeconds] = useState(0);
// State to control whether the timer is running or not
const [isActive, setIsActive] = useState(false);
useEffect(() => {
let interval = null;
if (isActive) {
// If the timer is active, set an interval to update the seconds
interval = setInterval(() => {
setSeconds((prevSeconds) => prevSeconds + 1);
}, 1000);
} else if (!isActive && seconds !== 0) {
// If the timer is paused, clear the interval
clearInterval(interval);
}
// Cleanup the interval when the component unmounts or on re-render
return () => clearInterval(interval);
}, [isActive, seconds]);
// Function to toggle the timer on and off
const toggleTimer = () => {
setIsActive(!isActive);
};
// Function to reset the timer
const resetTimer = () => {
setSeconds(0);
setIsActive(false);
};
return (
Elapsed time: {seconds} seconds
);
}
export default Timer;
1. useState
The useState
hook allows you to add state to functional components. It returns a pair: the current state value and a function to update it.
import React, { useState } from 'react';
function Counter() {
const [count, setCount] = useState(0); // count is the state variable, setCount is the state updater function.
return (
Current count: {count}
);
}
useState(0)
initializes the count
state variable with a value of 0.
The setCount
function is used to update the count
value.
2. useEffect
The useEffect
hook is used to handle side effects in functional components, such as fetching data, subscribing to events, or updating the DOM. It runs after the component renders and can be configured to run on specific state changes.
import React, { useState, useEffect } from 'react';
function Timer() {
const [seconds, setSeconds] = useState(0);
useEffect(() => {
const interval = setInterval(() => {
setSeconds(seconds => seconds + 1);
}, 1000);
return () => clearInterval(interval); // Cleanup function to prevent memory leaks.
}, []); // Empty dependency array ensures this effect runs only once, after the initial render.
return Elapsed time: {seconds} seconds
;
}
useEffect
sets up a timer that increments the seconds
state every second.
How It Works:
State Management:
seconds
: This state variable tracks how many seconds have passed.isActive
: This controls whether the timer is running or paused.useEffect
Hook:
useEffect
hook handles the interval. It starts a new interval when isActive
is true
and clears it when isActive
is false
or when the component unmounts.[isActive, seconds]
) ensures that the effect runs whenever isActive
or seconds
change.Functions:
toggleTimer
: Starts or pauses the timer.resetTimer
: Resets the timer to zero and pauses it.
4. The Lifecycle of a React Component
Every React component goes through a lifecycle that can be categorized into three main phases: Mounting, Updating, and Unmounting. Understanding these phases helps developers manage side effects, optimize performance, and ensure proper resource management.
1. Mounting
The mounting phase occurs when a component is being created and inserted into the DOM. Key lifecycle methods in this phase include:
2. Updating
The updating phase occurs when a component’s state or props change, causing it to re-render. Key lifecycle methods in this phase include:
false
can optimize performance by preventing unnecessary re-renders.3. Unmounting
The unmounting phase occurs when a component is being removed from the DOM. The primary lifecycle method in this phase is:
componentWillUnmount(): This method is invoked immediately before a component unmounts. It’s commonly used for cleanup tasks, such as cancelling network requests or removing event listeners.
5. Lifecycle Hooks in Functional Components
With the introduction of hooks, functional components can now manage side effects and lifecycle events using the useEffect
hook. This hook combines several lifecycle methods into one.
Using useEffect
The useEffect
hook runs after every render by default and can be configured to run only when specific dependencies change.
import React, { useState, useEffect } from 'react';
function Timer() {
const [seconds, setSeconds] = useState(0);
useEffect(() => {
const interval = setInterval(() => {
setSeconds((prevSeconds) => prevSeconds + 1);
}, 1000);
return () => clearInterval(interval); // Cleanup function runs before the component unmounts or before the next effect runs.
}, []); // Empty dependency array means this effect runs once after the initial render.
return Elapsed time: {seconds} seconds
;
}