0
0
NextJSframework~3 mins

Why Shared state across layouts in NextJS? - Purpose & Use Cases

Choose your learning style9 modes available
The Big Idea

What if your app could keep data perfectly synced everywhere without you lifting a finger?

The Scenario

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.

The Problem

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.

The Solution

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.

Before vs After
Before
function Layout1(props) { return <Cart items={props.cartItems} />; }
function Layout2(props) { return <Cart items={props.cartItems} />; }
// Pass cartItems down manually everywhere
After
const cart = useSharedCart();
function Layout1() { return <Cart items={cart.items} />; }
function Layout2() { return <Cart items={cart.items} />; }
// Cart state shared automatically across layouts
What It Enables

This makes it easy to build smooth, consistent apps where data stays updated across all pages and layouts without extra code.

Real Life Example

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.

Key Takeaways

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.