State

State is data that changes over time in an application. In frontend development, state determines what users see and how the UI responds to interactions.

React State

javascript
import { useState } from 'react'

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

  return (
    <div>
      <p>You clicked {count} times</p>
      <button onClick={() => setCount(count + 1)}>
        Click me
      </button>
    </div>
  )
}

Types of State

Local State Belongs to a single component.

Global State Shared across multiple components (Context, Redux, Zustand).

Server State Data from external sources (React Query, SWR).

URL State State stored in the URL (query parameters, route params).

State Management

javascript
// Local state
const [user, setUser] = useState(null)

// Context for global state
const ThemeContext = createContext()

// External library (Zustand)
const useStore = create((set) => ({
  count: 0,
  increment: () => set((state) => ({ count: state.count + 1 }))
}))

Best Practices

  • Keep state as local as possible
  • Derive data instead of duplicating state
  • Use the right state management solution
  • Avoid unnecessary re-renders
  • Make state updates predictable

State vs Props

State

  • Owned by component
  • Can be changed by component
  • Triggers re-renders when updated

Props

  • Passed from parent
  • Read-only in component
  • Changes come from parent

Learn More