This tutorial aims to provide a deep understanding of managing State and Lifecycle methods in React.
By the end of this tutorial, you will be able to:
- Understand the concept of State in React and how to use it
- Understand React's Lifecycle methods and how to use them
- Know how to manage State and use Lifecycle methods in your React applications
State in React is a built-in object that stores component data. It is mutable and can be accessed and updated throughout the component.
Lifecycle methods are special methods provided by React that allow us to run code at particular times in the process of a component's life cycle.
State is managed within the component (local state).
class MyComponent extends React.Component {
constructor(props) {
super(props);
// state is initialized
this.state = {
name: 'John',
};
}
}
Here, name
is a state variable initialized with the value 'John'.
Lifecycle methods are categorized into three parts: Mounting, Updating, and Unmounting.
These methods are called in the following order when an instance of a component is being created and inserted into the DOM:
- constructor()
- static getDerivedStateFromProps()
- render()
- componentDidMount()
An update can be caused by changes to props or state. These methods are called in this order when a component is being re-rendered:
- static getDerivedStateFromProps()
- shouldComponentUpdate()
- render()
- getSnapshotBeforeUpdate()
- componentDidUpdate()
This method is called when a component is being removed from the DOM:
- componentWillUnmount()
Here's an example of a simple counter application where state is used.
class Counter extends React.Component {
constructor(props) {
super(props);
// Initializing state
this.state = { count: 0 };
}
incrementCount = () => {
this.setState({ count: this.state.count + 1 });
};
render() {
return (
<div>
<p>You clicked {this.state.count} times</p>
<button onClick={this.incrementCount}>Click Me</button>
</div>
);
}
}
Here, count
is a state variable. The incrementCount
method updates the state. The render
method renders the state to the DOM.
Here's an example of a component using lifecycle methods.
class MyComponent extends React.Component {
constructor(props) {
super(props);
console.log('Constructor');
}
componentDidMount() {
console.log('componentDidMount');
}
componentDidUpdate() {
console.log('componentDidUpdate');
}
componentWillUnmount() {
console.log('componentWillUnmount');
}
render() {
console.log('Render');
return <div>My Component</div>;
}
}
In the console, you'll see logs for each lifecycle method as they get executed in order.
Next steps for learning would be understanding props in React, and how to pass data between components.
Create a React component with a state variable color
initialized as 'red'. Add a button that changes the state's color to 'blue'.
Create a React component that logs a message to the console in each lifecycle method.
Create a counter application where the counter value resets to zero after reaching 10. Implement this using state and lifecycle methods.
Here are the solutions for each exercise:
class ColorComponent extends React.Component {
constructor(props) {
super(props);
this.state = { color: 'red' };
}
changeColor = () => {
this.setState({ color: 'blue' });
};
render() {
return (
<div>
<p>The color is {this.state.color}</p>
<button onClick={this.changeColor}>Change color</button>
</div>
);
}
}
class LifecycleComponent extends React.Component {
constructor(props) {
super(props);
console.log('Constructor');
}
componentDidMount() {
console.log('componentDidMount');
}
componentDidUpdate() {
console.log('componentDidUpdate');
}
componentWillUnmount() {
console.log('componentWillUnmount');
}
render() {
console.log('Render');
return <div>Lifecycle Component</div>;
}
}
class Counter extends React.Component {
constructor(props) {
super(props);
this.state = { count: 0 };
}
componentDidUpdate() {
if (this.state.count > 10) {
this.setState({ count: 0 });
}
}
incrementCount = () => {
this.setState({ count: this.state.count + 1 });
};
render() {
return (
<div>
<p>You clicked {this.state.count} times</p>
<button onClick={this.incrementCount}>Click Me</button>
</div>
);
}
}
Keep practicing and exploring more about React!