Bird
Raised Fist0
NextJSframework~20 mins

Shared state across layouts in NextJS - Practice Problems & Coding Challenges

Choose your learning style10 modes available
Challenge - 5 Problems
🎖️
Shared State Mastery in Next.js
Get all challenges correct to earn this badge!
Test your skills under time pressure!
❓ component_behavior
intermediate
2:00remaining
How does shared state behave across nested layouts in Next.js 14?
Consider a Next.js 14 app with a root layout and a nested layout. Both layouts use React's useState to hold a counter. If the nested layout updates its counter, what happens to the root layout's counter?
NextJS
import React from 'react';

export default function RootLayout({ children }) {
  const [count, setCount] = React.useState(0);
  return <html><body>{children}</body></html>;
}

export function NestedLayout({ children }) {
  const [count, setCount] = React.useState(0);
  // Button to increment count
  return <section>{children}</section>;
}
AThe nested layout's counter update does not affect the root layout's counter; they are independent states.
BUpdating the nested layout's counter also updates the root layout's counter because state is shared automatically.
CThe root layout's counter resets to zero whenever the nested layout updates its counter.
DBoth counters merge and show the sum of their values automatically.
Attempts:
2 left
💡 Hint
Think about how React state works in separate components.
🧠 Conceptual
intermediate
2:00remaining
What is the recommended way to share state across layouts in Next.js 14?
You want to share a theme setting (dark/light) across multiple layouts in a Next.js 14 app. Which approach correctly shares this state?
APass state as props from nested layouts to root layout.
BDeclare useState separately in each layout and expect React to sync them automatically.
CUse localStorage in each layout without any React state management.
DUse React Context Provider at the root layout and consume context in nested layouts.
Attempts:
2 left
💡 Hint
Think about React's way to share data deeply without prop drilling.
🔧 Debug
advanced
2:00remaining
Why does the shared state reset when navigating between layouts in Next.js 14?
You implemented a React Context Provider in the root layout to share state. However, when navigating between pages with different nested layouts, the shared state resets unexpectedly. What is the likely cause?
AReact Context does not work across layouts in Next.js 14.
BThe root layout is unmounted and remounted on navigation, resetting state.
CYou forgot to wrap the nested layouts with the Context Provider.
DNext.js 14 disables React state persistence by default.
Attempts:
2 left
💡 Hint
Consider how Next.js handles layouts and navigation.
📝 Syntax
advanced
2:00remaining
Which code snippet correctly implements a shared state using React Context in Next.js 14 layouts?
Select the code snippet that correctly creates and uses a React Context Provider in the root layout and consumes it in a nested layout.
A
const ThemeContext = React.createContext();

export default function RootLayout({ children }) {
  const [theme, setTheme] = React.useState('light');
  return &lt;ThemeContext.Provider value={{ theme }}&gt;{children}&lt;/ThemeContext.Provider&gt;;
}

export function NestedLayout({ children }) {
  const theme = React.useContext(ThemeContext);
  return &lt;div className={theme}&gt;{children}&lt;/div&gt;;
}
B
const ThemeContext = React.createContext();

export default function RootLayout({ children }) {
  const [theme, setTheme] = React.useState('light');
  return &lt;ThemeContext.Provider value={theme}&gt;{children}&lt;/ThemeContext.Provider&gt;;
}

export function NestedLayout({ children }) {
  const theme = React.useContext(ThemeContext);
  return &lt;div className={theme}&gt;{children}&lt;/div&gt;;
}
C
const ThemeContext = React.createContext();

export default function RootLayout({ children }) {
  const [theme, setTheme] = React.useState('light');
  return &lt;ThemeContext.Provider value={{ theme, setTheme }}&gt;{children}&lt;/ThemeContext.Provider&gt;;
}

export function NestedLayout({ children }) {
  const { theme } = React.useContext(ThemeContext);
  return &lt;div className={theme}&gt;{children}&lt;/div&gt;;
}
D
const ThemeContext = React.createContext('light');

export default function RootLayout({ children }) {
  const theme = 'light';
  return &lt;ThemeContext.Provider value={theme}&gt;{children}&lt;/ThemeContext.Provider&gt;;
}

export function NestedLayout({ children }) {
  const { theme } = React.useContext(ThemeContext);
  return &lt;div className={theme}&gt;{children}&lt;/div&gt;;
}
Attempts:
2 left
💡 Hint
Check how the context value is passed and destructured.
❓ state_output
expert
2:00remaining
What is the output after clicking the increment button twice in this shared state example across layouts?
Given the root layout provides a counter state via React Context, and the nested layout renders a button to increment it, what is the displayed counter value after clicking the button twice?
NextJS
import React from 'react';

const CounterContext = React.createContext();

export default function RootLayout({ children }) {
  const [count, setCount] = React.useState(0);
  return (
    <CounterContext.Provider value={{ count, setCount }}>
      <html><body>{children}</body></html>
    </CounterContext.Provider>
  );
}

export function NestedLayout({ children }) {
  const { count, setCount } = React.useContext(CounterContext);
  return (
    <section>
      <p>Count: {count}</p>
      <button onClick={() => setCount(count + 1)}>Increment</button>
      {children}
    </section>
  );
}
ACount: 2
BCount: 1
CCount: 0
DCount: NaN
Attempts:
2 left
💡 Hint
Each click increases count by 1 starting from zero.

Practice

(1/5)
1. What is the main benefit of sharing state across layouts in Next.js?
easy
A. It allows multiple layouts and pages to access the same data easily.
B. It improves the styling of components automatically.
C. It speeds up the server response time by caching data.
D. It prevents users from navigating between pages.

Solution

  1. Step 1: Understand the purpose of shared state

    Shared state means multiple parts of the app can use the same data without duplication.
  2. Step 2: Identify the benefit in Next.js layouts

    Sharing state across layouts lets pages and layouts access common data easily, improving consistency.
  3. Final Answer:

    It allows multiple layouts and pages to access the same data easily. -> Option A
  4. Quick Check:

    Shared state = common data access [OK]
Hint: Shared state means one data source for many layouts [OK]
Common Mistakes:
  • Confusing shared state with styling or caching
  • Thinking shared state blocks navigation
  • Assuming shared state only affects server speed
2. Which of the following is the correct way to provide shared state in Next.js layouts using React Context?
easy
A. Import state from a CSS file and use it in layouts.
B. Wrap the root layout with a Context Provider component.
C. Use getServerSideProps to pass state to layouts.
D. Add state variables directly inside each layout without a provider.

Solution

  1. Step 1: Recall React Context usage

    React Context requires wrapping components with a Provider to share state.
  2. Step 2: Apply to Next.js layouts

    Wrapping the root layout with the Provider shares state across all nested layouts and pages.
  3. Final Answer:

    Wrap the root layout with a Context Provider component. -> Option B
  4. Quick Check:

    Provider wraps root layout = shared state [OK]
Hint: Always wrap root layout with Provider for shared state [OK]
Common Mistakes:
  • Trying to add state without a Provider
  • Using server props instead of Context for shared state
  • Confusing CSS imports with state management
3. Given this code snippet in a Next.js app, what will be the output when clicking the button in any nested layout?
const CountContext = React.createContext();

function CountProvider({ children }) {
  const [count, setCount] = React.useState(0);
  return (
    <CountContext.Provider value={{ count, setCount }}>
      {children}
    </CountContext.Provider>
  );
}

function Button() {
  const { count, setCount } = React.useContext(CountContext);
  return <button onClick={() => setCount(count + 1)}>Clicked {count} times</button>;
}

// Root layout wraps children with <CountProvider>
medium
A. Clicking the button increases the count visible in all layouts sharing the context.
B. Clicking the button only updates the count inside the Button component itself.
C. Clicking the button causes a runtime error because context is not provided.
D. Clicking the button resets the count to zero every time.

Solution

  1. Step 1: Understand context sharing

    The CountProvider shares count state via context to all nested components.
  2. Step 2: Analyze button behavior

    Clicking the button calls setCount to increase count, updating all components using the context.
  3. Final Answer:

    Clicking the button increases the count visible in all layouts sharing the context. -> Option A
  4. Quick Check:

    Context state update = shared count change [OK]
Hint: Context updates reflect everywhere wrapped by Provider [OK]
Common Mistakes:
  • Thinking state updates are local to Button only
  • Assuming missing Provider causes error here
  • Believing count resets on each click
4. You have wrapped your root layout with a Context Provider, but nested layouts cannot access the shared state. What is the most likely cause?
medium
A. You placed the Provider inside a nested layout instead of the root layout.
B. You used React.useState instead of React.useContext in the root layout.
C. You forgot to use the custom hook or React.useContext inside nested layouts.
D. You imported the context from a CSS file instead of a JavaScript file.

Solution

  1. Step 1: Check how nested layouts access context

    Nested layouts must use React.useContext or a custom hook to read shared state.
  2. Step 2: Identify common mistake

    Forgetting to call useContext means no access to the shared data, even if Provider is correct.
  3. Final Answer:

    You forgot to use the custom hook or React.useContext inside nested layouts. -> Option C
  4. Quick Check:

    Missing useContext call = no access [OK]
Hint: Use useContext hook inside nested layouts to access shared state [OK]
Common Mistakes:
  • Placing Provider too deep, not at root
  • Confusing useState with useContext
  • Importing context incorrectly from non-JS files
5. You want to share a user authentication state across multiple layouts in Next.js. Which approach correctly combines shared state with server-side data fetching to keep the user logged in?
hard
A. Use local component state in each layout to store user info fetched from the server on mount.
B. Store user data only in getServerSideProps and pass it as props to each layout without using Context.
C. Save user info in a CSS variable and read it in layouts for shared state.
D. Wrap the root layout with a Context Provider that holds user state, and update it client-side after fetching user info in a server action or API route.

Solution

  1. Step 1: Understand combining server data with shared state

    User info fetched server-side should be stored in a shared client state for consistent access.
  2. Step 2: Use Context Provider at root layout

    Wrapping root layout with a Provider holding user state allows all layouts to access and update it.
  3. Step 3: Update state client-side after server fetch

    Fetching user info via server actions or API routes and updating context keeps user logged in across layouts.
  4. Final Answer:

    Wrap the root layout with a Context Provider that holds user state, and update it client-side after fetching user info in a server action or API route. -> Option D
  5. Quick Check:

    Context + server fetch = shared auth state [OK]
Hint: Use Context Provider plus server fetch to share auth state [OK]
Common Mistakes:
  • Passing user data only via props without shared state
  • Using local state per layout causing inconsistent user info
  • Trying to store user info in CSS or non-JS files
Recommended

Ready to prove it?

Pass the test and this pattern moves unknown strong while earning +1 Grip toward your certificate.

10 questions~5 mineasy hard