Andrew Leonenko
Andrew Leonenko

Software Engineer

Understanding State Management in React 🎛️

Managing state is one of the most important aspects of React development. In this post, we’ll explore the different types of state, tools for managing it, and examples of how to use state effectively.


What is State in React?

State represents dynamic data that influences the behavior and rendering of your application. React manages state in two main categories:

  1. Local State: Managed within a single component.
  2. Global State: Shared across multiple components.

Example: Local State with useState

Using the useState hook to manage form inputs:

import React, { useState } from 'react'

function Form() {
  const [inputValue, setInputValue] = useState('')

  const handleChange = (e) => {
    setInputValue(e.target.value)
  }

  return (
    <div>
      <input type="text" value={inputValue} onChange={handleChange} />
      <p>You typed: {inputValue}</p>
    </div>
  )
}

export default Form

Example: Global State with useContext

Using the useContext hook to manage global state:

import React, { useContext } from 'react'
import { MyContext } from './MyContext'

function MyComponent() {
  const { globalState, setGlobalState } = useContext(MyContext)

  const handleClick = () => {
    setGlobalState(!globalState)
  }

  return (
    <div>
      <button onClick={handleClick}>
        {globalState ? 'Global State is ON' : 'Global State is OFF'}
      </button>
    </div>
  )
}

export default MyComponent

Written by Andrew Leonenko

Andrew Leonenko

I'm a seasoned software engineer passionate about building products that make a difference. I specialize in web development and love exploring new technologies.

Check my Bio