Open In App

Implementing State in React Components

In React State is an object that holds some information which can be changed overtime. Whenever a State is updated it triggers re-rendering of the component. In React components State can be implemented by default in class components and in functional components we have to implement state using hooks.

Approaches To Implementing State in React

There are two ways to implement state in React Components based upon the type of component

Implementing State Using this.state object

Implement State using this.state Example :

This example creates a counter in react by implementing state using the above mentioned approach






import React, { Component } from "react";
 
class App extends React.Component {
    constructor() {
        super();
        this.state = {
            count: 0,
        };
        this.increase = this.increase.bind(this);
    }
 
    increase() {
        this.setState({ count: this.state.count + 1 });
    }
 
    render() {
        return (
            <div style={{ margin: "50px" }}>
                <h1>Welcome to Geeks for Geeks </h1>
                <h3>Counter App using Class Component : </h3>
                <h2> {this.state.count}</h2>
                <button onClick={this.increase}> Add</button>
            </div>
        );
    }
}
 
export default App;

Output:

Implementing State using useState hook:

Implement state using react hooks Example:

This example creates a counter by implementing state using the above mentioned approach




import React, { useState } from "react";
 
const App = () => {
    const [count, setCount] = useState(0);
 
    const increase = () => {
        setCount(count + 1);
    }
 
    return (
        <div style={{ margin: '50px' }}>
            <h1>Welcome to Geeks for Geeks </h1>
            <h3>Counter App using Functional Component : </h3>
            <h2>{count}</h2>
            <button onClick={increase}>Add</button>
        </div>
    )
}
 
export default App;

Output:

Conclusion:

States can be implemented in React by both functional and class components but to implement state in functional component we have to import the useState hook but state can be implemented directly in class component using the this.state object. States are useful as they are mutable unlike props and can helps us to create dynamic and interactive interfaces


Article Tags :