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:
- Local State: Managed within a single component.
- 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