What if your app could keep data perfectly synced everywhere without you lifting a finger?
Why Shared state across layouts in NextJS? - Purpose & Use Cases
Imagine you have a website with multiple pages, each using a different layout. You want to keep a shopping cart updated and visible no matter which page or layout the user visits.
Manually passing the cart data between layouts and pages means writing lots of repetitive code. It's easy to forget to update the cart everywhere, causing inconsistent or broken user experiences.
Shared state across layouts lets you keep data like the shopping cart in one place. All layouts can access and update it automatically, so the cart stays in sync everywhere without extra work.
function Layout1(props) { return <Cart items={props.cartItems} />; }
function Layout2(props) { return <Cart items={props.cartItems} />; }
// Pass cartItems down manually everywhereconst cart = useSharedCart();
function Layout1() { return <Cart items={cart.items} />; }
function Layout2() { return <Cart items={cart.items} />; }
// Cart state shared automatically across layoutsThis makes it easy to build smooth, consistent apps where data stays updated across all pages and layouts without extra code.
On an online store, the cart icon in the header updates instantly as you add items, no matter which page or layout you are on.
Manually syncing data across layouts is repetitive and error-prone.
Shared state lets all layouts access the same data automatically.
This creates seamless, consistent user experiences across pages.