Local vs. Global State Management
Learn about local and global state management in Next.js.
We'll cover the following...
Let’s take a closer look at the two different types of states that Next.js encompasses.
Local state management
When talking about local state management, we’re referring to the application state that is component-scoped. We can summarize that concept with an elementary Counter
component:
import React, { useState } from "react";function Counter({ initialCount = 0 }) {const [count, setCount] = useState(initialCount);return (<div><b>Count is: {count}</b><br /><button onClick={() => setCount(count + 1)}>Increment +</button><button onClick={() => setCount(count - 1)}>Decrement -</button></div>)}export default Counter;
When we click the “Increment” button, we’ll add 1
to the current count
value. Vice-versa, we’ll subtract 1
from that value when we click the “Decrement” button; nothing special!
But while it’s easy for a parent component to pass an initialCount
value as a prop for the Counter
element, it can be way more challenging to do the opposite: passing the current count
value to the parent component. There are many cases where we need to manage just the local state, and the React useState
hook can be ...