Mastering React JS: State & Lifecycle Methods 2025
React JS provides an efficient way to build dynamic and interactive UIs using components. Understanding State and Lifecycle Methods is crucial to managing component behavior and rendering efficiently.
What is State in React?
State is an object that holds data specific to a component and determines how the component renders and behaves.
Example: Managing State in a Component
import React, { Component } from 'react';
class Counter extends Component {
constructor(props) {
super(props);
this.state = { count: 0 };
}
increment = () => {
this.setState({ count: this.state.count + 1 });
}
render() {
return (
Count: {this.state.count}
);
}
}
export default Counter;
Here, this.state holds the count, and setState updates it when the button is clicked.
React Lifecycle Methods
React components go through various phases. These phases are controlled using lifecycle methods.
Mounting Phase
This phase happens when a component is being created and inserted into the DOM.
- constructor() - Initializes state and binds methods.
- render() - Returns the JSX to be displayed.
- componentDidMount() - Executes after the component is mounted.
Example: componentDidMount()
componentDidMount() {
console.log("Component has been mounted");
}
Updating Phase
Occurs when a component is re-rendered due to state or prop changes.
- shouldComponentUpdate() - Determines if re-render is needed.
- componentDidUpdate() - Executes after state or props update.
Example: componentDidUpdate()
componentDidUpdate(prevProps, prevState) {
console.log("Component updated from", prevState, "to", this.state);
}
Unmounting Phase
Happens when a component is removed from the DOM.
- componentWillUnmount() - Cleans up resources (e.g., event listeners).
Example: componentWillUnmount()
componentWillUnmount() {
console.log("Component is being removed");
}
React Hooks Alternative
With hooks, you can manage state and lifecycle within functional components using useState and useEffect.
Example: useState and useEffect
import React, { useState, useEffect } from 'react';
function Counter() {
const [count, setCount] = useState(0);
useEffect(() => {
console.log("Component mounted or updated");
return () => console.log("Component will unmount");
}, [count]);
return (
Count: {count}
);
}
export default Counter;
Conclusion
Understanding State and Lifecycle Methods is essential for React developers. With class components, we use lifecycle methods, while functional components leverage hooks for state and side effects.