State in React

Any web app has a state. e.g. User is logged in, User has entered data in a form, User has opened the menu. In react all this information can be stored in an object called as state. Each component can have unique state. As user interacts with the application, state of the app/component keeps changing. Based on state changes, component gets updated. In big react applications, we usually need to use useReducer hook or redux to manage the state.

Example

In below example, we have a state to store the counter. When user clicks on Increment or decrement buttons, setCount (aka. setState) is called and state is updated. Once state is updated, new count is displayed on UI after component is re-rendered.

import React, { useState } from "react";
import "./styles.css";

export default function Main() {

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

  let clickIncrement = () => {
    setCount((prevCount) => {
      return ++prevCount;
    });
  };

  let clickDecrement = () => {
    setCount((prevCount) => {
      return --prevCount;
    });
  };

  return (
    <div className="Main">
      <div>{count}</div>
      <button onClick={clickIncrement}>Increment</button>
      <button onClick={clickDecrement}>Decrement</button>
    </div>
  );
}

Complex problems, Simple Solutions