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
useState
Using the
useState
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
useContext
Using the
useContext
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;