How to use state in React

Using state allows React components to store and update data that changes over time, triggering re-renders when values change. As the creator of CoreUI, a widely used open-source UI library, I’ve implemented state management in thousands of React components for enterprise applications. From my expertise, the most effective approach is using the useState hook with proper initialization. This method provides simple state management and predictable component behavior.

Use the useState hook to declare state variables with initial values and update functions.

import { useState } from 'react'

function Counter() {
  const [count, setCount] = useState(0)

  return (
    <div>
      <p>Count: {count}</p>
      <button onClick={() => setCount(count + 1)}>
        Increment
      </button>
    </div>
  )
}

The useState hook returns an array with the current state value and setter function. Pass the initial value to useState, then use the setter function to update state. When state changes, React automatically re-renders the component with the new value. Use functional updates when new state depends on previous value.

Best Practice Note:

This is the same approach we use in CoreUI React components for state management.


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

Subscribe to our newsletter
Get early information about new products, product updates and blog posts.
What is the difference between sort and toSorted in JavaScript?
What is the difference between sort and toSorted in JavaScript?

How to Use JavaScript setTimeout()
How to Use JavaScript setTimeout()

How to get element ID in JavaScript
How to get element ID in JavaScript

How to convert a string to boolean in JavaScript
How to convert a string to boolean in JavaScript

Answers by CoreUI Core Team