DEV Community

Cover image for What is State in React?
Navindu Abhishek
Navindu Abhishek

Posted on

What is State in React?

React state is like some kind of storage. It can save values that belong to the component. Like form data or some kind of data like that change-over button click or any user interaction. When the state changes, the component re-renders itself. It automatically updates the changes in content and shows them to the user. This concept is more efficient because React only updates part of the component, not the entire DOM.

In the past, state could only be used in class components, but with React Hooks introduced in React 16.8, you can now use state in functional components too! This makes your code cleaner and easier to understand. One of the hooks provided by React for managing state in functional components is useState().

Lets discuss using two simple examples

  1. Counter App
import React, { useState } from 'react';

function Counter() {
  // Initializing state
  const [count, setCount] = useState(0);

  // Function to increment count
  const incrementCount = () => {
    setCount(count + 1);
  };

  // Function to decrement count
  const decrementCount = () => {
    setCount(count - 1);
  };

  return (
    <div>
      <p>The count is: {count}</p>
      <button onClick={incrementCount}>Click me to increase count</button>
      <button onClick={decrementCount}>Click me to decrease count</button>
    </div>
  );
}

export default Counter;
Enter fullscreen mode Exit fullscreen mode

This block of code defines a functional component named Counter. It's a simple component that shows a count on the screen and provides buttons to either increment or decrement that count.

const [count, setCount] = useState(0) initializes the component's state. useState(0) means that count starts with a value of 0.

count is the current state value, and setCount is a function that updates this value. This is what "state" in React refers to: data that can change over time.

function increases and decreases the count by 1 whenever it's called. React automatically re-renders the component with the updated state, showing the new count on the screen.

  1. Toggle Message
import React, { useState } from 'react';

function ToggleMessage() {
  // Initialize state with the initial message
  const [message, setMessage] = useState("Hello, World!");

  // Function to toggle the message
  const toggleMessage = () => {
    setMessage(prevMessage => prevMessage === "Hello, World!" ? "Goodbye, World!" : "Hello, World!");
  };

  return (
    <div>
      <p>{message}</p>
      <button onClick={toggleMessage}>Toggle Message</button>
    </div>
  );
}

export default ToggleMessage;
Enter fullscreen mode Exit fullscreen mode

The toggleMessage function changes the state based on its current value. If the message is "Hello, World!", it switches to "Goodbye, World!" and vice versa. It uses setMessage to update the state, and employs a callback function (prevMessage => …) to access the current state value and decide the new state based on it.

After Clicking the button invokes toggleMessage, toggling the state between "Hello, World!" and "Goodbye, World!", which in turn updates the displayed message.

I hope this explanation helps clarify the concept of state in React. I encourage you to follow best practices in React development and continue exploring its powerful features!

Sentry blog image

How I fixed 20 seconds of lag for every user in just 20 minutes.

Our AI agent was running 10-20 seconds slower than it should, impacting both our own developers and our early adopters. See how I used Sentry Profiling to fix it in record time.

Read more

Top comments (0)

Billboard image

The Next Generation Developer Platform

Coherence is the first Platform-as-a-Service you can control. Unlike "black-box" platforms that are opinionated about the infra you can deploy, Coherence is powered by CNC, the open-source IaC framework, which offers limitless customization.

Learn more

👋 Kindness is contagious

Please leave a ❤️ or a friendly comment on this post if you found it helpful!

Okay