DEV Community

Mitchel Gitau
Mitchel Gitau

Posted on

Understanding useState in React

useState is a native state management hook in React that allows components to keep track of state between renders.

Logical Breakdown of useState:

  1. Define the initial state:
    • useState(10) → Initializes a number.
    • useState("") → Initializes an empty string.
    • useState(() => "Jack") → Uses a lazy initialization function.
  2. Destructure the returned array:

    • useState returns an array with two values:
      • The current state value
      • A function to update the state
    • Example:

      const [name, setName] = useState("");
      
  3. Update state using the setter function (setState)

    • Directly modifying the state variable won't trigger a re-render.
    • Always use the setter function to update state:

      setName("Alice"); // Correct 
      name = "Alice"; // Won't update state
      

Why use setState instead of modifying the variable?

  • For primitive data types (numbers, strings, booleans):
    • Changing the variable only creates a local copy. React won’t recognize the change*.*
  • For reference types (arrays, objects):
    • Modifying the variable directly mutates the original state, which React might not track.
    • Best practice is to spread the existing state and then update it.

Updating an Array in State (Best Practice)

const [items, setItems] = useState(["Apple", "Banana"]);

// Incorrect(Direct mutation)
items.push("Orange");
setItems(items);

// Correct (Create a new array)
setItems([...items, "Orange"]);

Enter fullscreen mode Exit fullscreen mode

Updating an Object in State (Best Practice)

const [user, setUser] = useState({ name: "Jack", age: 25 });

// Incorrect (Direct mutation)
user.name = "Alice";
setUser(user);

// Correct (Create a new object)
setUser({ ...user, name: "Alice" });

Enter fullscreen mode Exit fullscreen mode

Top comments (0)