State in React.js with Examples

 

State in React.js with Examples

State is a built-in object in React that allows components to store and manage data that can change over time. Unlike props, which are immutable, state is mutable and can be updated using the setState method (in class components) or useState hook (in functional components).


1. State in Functional Components (Using Hooks - useState)

Since React 16.8, functional components can use state with the useState hook.

import React, { useState } from "react";

 

import React, { useState } from 'react';

 

function Counter()

{

    const [count,setCount] = useState(0);

 

    return(

        <div>

            <h1>Counter : {count}</h1>

            <button onClick={()=>setCount(count + 1)}>Increment</button>

            <button onClick={()=>setCount(count - 1)}>Decrement</button>

        </div>

    )

}

 

export default Counter;

Explanation:

  • useState(0) initializes the state variable count with 0.
  • setCount updates the state when the buttons are clicked.
  • The component re-renders when the state changes.

2. State in Class Components (this.state)

In class components, state is managed using this.state and updated using this.setState().

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})

    }

 

    decrement = () =>{

        this.setState({count:this.state.count-1})

    }

 

    render()

    {

        return(

        <div>

            <h1>Counter:{this.state.count} </h1>

            <button onClick={this.increment}>Increment</button>

            <button onClick={this.decrement}>Decrement</button>

        </div>

        )

    }

 

}

 

export default Counter;

Explanation:

  • this.state = { count: 0 } initializes the state.
  • this.setState({ count: this.state.count + 1 }) updates the state and re-renders the component.
  • Methods increment and decrement modify the state when buttons are clicked.

Key Differences Between State in Functional and Class Components

Feature

Functional Component (useState)

Class Component (this.state)

Syntax

const [state, setState] = useState(initialValue);

this.state = { key: value };

State Updates

Uses setState(value)

Uses this.setState({ key: value })

Simplicity

More concise and readable

More verbose

Performance

Preferred in modern React (lightweight)

Uses this binding, slightly less efficient


Conclusion

  • Use Functional Components (useState) for modern React applications.
  • Use Class Components (this.state) when working with legacy code.
  • The useState hook is simpler and preferred for handling state in functional components.

 

Comments

Popular posts from this blog

Axios in React.js

Conditions in React.js

Applying map() Function in React.js (Arrays & Objects)