DEV Community

Cover image for ๐Ÿง  Understanding useState in React
Rishabh Joshi
Rishabh Joshi

Posted on โ€ข Edited on

๐Ÿง  Understanding useState in React

React is all about building dynamic UIs โ€” and to do that, we need state. One of the most fundamental hooks in React is useState.

This post is a simplified and structured guide created from my personal notes, designed to help beginners understand how useState works, when to use it, and follow best practices.


๐Ÿš€ What is useState?

useState is a Hook in React that lets you add state to functional components. It allows your component to remember values between renders and update the UI when that value changes.

const [state, setState] = useState(initialValue);
Enter fullscreen mode Exit fullscreen mode
  • state โ†’ The current state value
  • setState โ†’ A function to update the state
  • initialValue โ†’ The initial value of the state (can be a primitive, object, array, or function)

๐Ÿ›  Basic Example

import { useState } from "react";

export default function App() {
  const [step, setStep] = useState(1);
  {/*here step stores the default value i.e. 1 and 2nd parameter
  is the function which will help us updating the value of state.*/}

  function handlePrevious() {
    setStep(step + 1);
    {/* NEVER update state based on current state like this
    (use callback function)*/}
  }

  return (
    <div className="buttons">
      <p className="message">Step {step}</p>
      <button onClick={handlePrevious}>Previous</button>
    </div>
  );
}
Enter fullscreen mode Exit fullscreen mode

๐Ÿ“ Note

  • useState is a hook โ€” and hooks must be used at the top level of your component.
  • Never update state directly โ€” always use the setter function

React REACTS to state changes by re-rendering the UI


๐Ÿ” The Mechanics of State

  • Whenever the state updates, React re-renders the component.
  • State is preserved between re-renders โ€” unless the component unmounts (i.e. disappears from UI).
  • React calls the function of your component again during re-render, but the state remains intact.

โšก Tips for Using State Effectively

โœ… Make sure to update state only when needed, to avoid performance issues.
โœ… Use callback functions when your new state depends on the current one.
โŒ Avoid using state to store values that can be calculated from props.
โœ… Use state to store data specific to the component.
โŒ Never mutate the state directly.


โŒ Donโ€™t update based on current state like this:

setStep(step - 1);
Enter fullscreen mode Exit fullscreen mode

โœ… Use callback function when state depends on current value:

setStep((curStep) => curStep - 1);
Enter fullscreen mode Exit fullscreen mode

If updating state doesnโ€™t depend on the current state, you can use the direct method.


๐Ÿงฉ State Management in React

  • State management is about deciding:

    • What state is needed?
    • Where it should live?
    • How data flows through the app?
  • Local State:

    • Needed in one or a few components.
    • Passed via props if needed by child components.
  • Global State:

    • Shared across many components.
    • Use tools like Context API or Redux.

โฌ†๏ธ Lifting the State Up
If sibling components need the same piece of state, lift it to the nearest common parent.

๐Ÿ“ Derived State
Derived state is calculated based on another piece of state or prop โ€” and recalculated during every render.


๐ŸŽฎ Controlled Elements in React

By default, input fields manage their own state in the DOM. In React, we like to centralize state inside our app. This is done using controlled elements.

Steps to implement:

  1. Create state for the input.
  2. Set input's value to that state.
  3. Use onChange to update the state.
function Form() {
  const [description, setDescription] = useState("");

  function handleSubmit(e) {
    e.preventDefault();
  }

  return (
    <form onSubmit={handleSubmit}>
      <input
        type="text"
        placeholder="Item.."
        value={description}
        onChange={(e) => setDescription(e.target.value)}
      />
   {/* setting the value of item as state and then 
   updating the value of state by using setter function */}
    </form>
  );
}
Enter fullscreen mode Exit fullscreen mode

๐Ÿ”š Conclusion

**useState** is your first and most important hook in React. Understanding how it works, when to use callbacks, and how to structure state effectively will set you up for success in building dynamic, interactive UIs.

Happy coding! ๐Ÿ’ปโœจ


๐Ÿ™Œ Letโ€™s Connect

Iโ€™d love to hear your thoughts, questions, or feedback.
You can reach me on GitHub or leave a comment below.

Hot sauce if you're wrong - web dev trivia for staff engineers

Hot sauce if you're wrong ยท web dev trivia for staff engineers (Chris vs Jeremy, Leet Heat S1.E4)

  • Shipping Fast: Test your knowledge of deployment strategies and techniques
  • Authentication: Prove you know your OAuth from your JWT
  • CSS: Demonstrate your styling expertise under pressure
  • Acronyms: Decode the alphabet soup of web development
  • Accessibility: Show your commitment to building for everyone

Contestants must answer rapid-fire questions across the full stack of modern web development. Get it right, earn points. Get it wrong? The spice level goes up!

Watch Video ๐ŸŒถ๏ธ๐Ÿ”ฅ

Top comments (0)

๐Ÿ‘‹ Kindness is contagious

DEV is better (more customized, reading settings like dark mode etc) when you're signed in!

Okay