React › State Management
What is the difference between local state and global state in a React app?
IntermediateAnswer
Local state belongs to a single component and is not needed anywhere else, such as whether a specific dropdown is open. Global state is data that many different, often unrelated components across the app need to read or update, such as the currently logged in user or the shopping cart contents.
// Local state, only this component cares about it
function Dropdown() {
const [isOpen, setIsOpen] = useState(false);
}
// Global state, needed by many different components across the app
const CartContext = React.createContext();Real-world example A dropdown menu's open or closed status stays as simple local state inside that one component, while the shopping cart contents are lifted into global state so the header, the cart page, and the checkout page can all access the same data.