How to update state in React

Updating state properly in React is fundamental for creating responsive and predictable user interfaces that trigger re-renders when data changes. As the creator of CoreUI, a widely used open-source UI library, I’ve implemented state updates in thousands of React components for form handling, data manipulation, and user interactions across enterprise applications. From my expertise, the most effective approach is to use the setState function with immutability patterns. This method ensures proper React re-renders, maintains state history for debugging, and prevents common bugs related to state mutations.

Use the setState function with immutability patterns to properly update React state and trigger re-renders.

import { useState } from 'react'

function StateUpdate() {
  const [count, setCount] = useState(0)
  const [user, setUser] = useState({ name: '', email: '' })
  const [items, setItems] = useState([])

  // Simple updates
  const increment = () => setCount(count + 1)
  const incrementSafely = () => setCount(prev => prev + 1)

  // Object updates (immutable)
  const updateUser = (name) => {
    setUser({ ...user, name })
  }

  // Array updates
  const addItem = (text) => {
    setItems([...items, { id: Date.now(), text }])
  }

  const removeItem = (id) => {
    setItems(items.filter(item => item.id !== id))
  }

  return (
    <div>
      <p>Count: {count}</p>
      <button onClick={increment}>Increment</button>
      <button onClick={incrementSafely}>Increment Safely</button>

      <input
        value={user.name}
        onChange={(e) => updateUser(e.target.value)}
        placeholder="Name"
      />
    </div>
  )
}

State updates in React must be immutable - never modify the existing state directly. Use the spread operator (…) to create new objects and arrays. For functional updates, pass a function to setState that receives the previous state, which is safer for updates that depend on the current state. When updating nested objects, spread each level of nesting.

Best Practice Note:

This is the same approach we use in CoreUI React components for reliable state management and optimal re-rendering performance.


Speed up your responsive apps and websites with fully-featured, ready-to-use open-source admin panel templates—free to use and built for efficiency.


About the Author