Logo
READLEARNKNOWCONNECT
Back to Lessons

    Page

  • - What is State?
  • - The useState Hook
  • - Updating State Correctly
  • - State with Different Data Types
  • - Updating Objects and Arrays in State
  • - Mini Project Step

6. State Management with useState

Level: BeginnerDuration: 18m

What is State?

State is data that changes over time in your component. Unlike props, which come from outside, state belongs to a component. When state changes, the component automatically re-renders.

The useState Hook

React gives us a built-in hook called useState to add state to functional components.

jsx
import { useState } from 'react'

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

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

export default Counter

`useState(0)` sets the initial state to 0. It returns an array with two items: the current state value (`count`) and a function to update it (`setCount`).

Updating State Correctly

State updates must be done using the updater function. Never change state directly like `count++`, that won't trigger a re-render.

jsx
// Correct
setCount(count + 1)

// Incorrect
// count = count + 1 ❌

State with Different Data Types

  • Strings – `useState('Hello')`
  • Numbers – `useState(0)`
  • Booleans – `useState(false)`
  • Arrays – `useState([])`
  • Objects – `useState({})`

Updating Objects and Arrays in State

When using objects or arrays, always create a copy before updating state to avoid accidental mutations.

jsx
// Updating an object
const [user, setUser] = useState({ name: 'Ada', age: 25 })
setUser({ ...user, age: 26 })

// Updating an array
const [items, setItems] = useState([1, 2, 3])
setItems([...items, 4])

Mini Project Step

Add a button to your `Header.jsx` component that toggles light and dark mode text. Use useState to manage a `theme` value that changes between 'light' and 'dark'. Update the style based on the theme.

jsx
// Header.jsx
import { useState } from 'react'

function Header() {
  const [theme, setTheme] = useState('light')

  return (
    <header>
      <h1>React Course Project</h1>
      <button onClick={() => setTheme(theme === 'light' ? 'dark' : 'light')}>
        Toggle Theme
      </button>
      <p>Current theme: {theme}</p>
    </header>
  )
}

export default Header