State in react
Created on: Sep 13, 2024
In React, state is a JavaScript object that stores data about a component and allows it to remember information between renders.
Below is class based example to demonstrate state. Here if we update counter, react automatically reflect the changes.
import React from "react"; class Counter extends React.Component { constructor(props) { super(props); this.state = { count: 0, }; } increment = () => { this.setState((prevState, props) => ({ count: prevState.count + 1, })); }; decrement = () => { this.setState((prevState) => ({ count: prevState.count - 1, })); }; render() { return ( <div> <h1>The current count is : {this.state.count}</h1> <button onClick={this.increment}>Increase</button> <button onClick={this.decrement}>Decrease</button> </div> ); } } export default Counter;
Equivalent code in functional component.
import React, { useState } from "react"; function CounterFn() { const [state, setState] = useState(0); let increment = () => { setState(state + 1); }; let decrement = () => { setState(state - 1); }; return ( <div> <h1>The current count is : {state}</h1> <button onClick={increment}>Increase</button> <button onClick={decrement}>Decrease</button> </div> ); } export default CounterFn;
Checkout whole code in my github repo
Important points
- State is local to a component instance on the screen. In other words, if you render the same component twice, each copy will have completely isolated state! Changing one of them will not affect the other.
- Unlike props, state is fully private to the component declaring it. The parent component can’t change it. This lets you add state to any component or remove it without impacting the rest of the components.
- The state should never be updated explicitly. React uses an observable object as the state that observes what changes are made to the state and helps the component behave accordingly.
setState
is used to update the state in class based component. In functional component we can use method that is used in initialization of state.