📖 Scenario: You are building a Next.js app with two different layouts: a main layout and a dashboard layout. You want to share a simple piece of state, a theme string, between these layouts so the user can switch the theme and see it update everywhere.
🎯 Goal: Create a shared state for theme using React context in Next.js. Use this shared state in two different layouts to show the current theme and a button to toggle it.
📋 What You'll Learn
Create a React context to hold the theme state and a function to toggle it
Wrap the app with the context provider in the root layout
Use the shared theme state in the main layout to display and toggle the theme
Use the shared theme state in the dashboard layout to display the current theme
💡 Why This Matters
🌍 Real World
Sharing state like theme, user login info, or settings across different parts of a Next.js app with multiple layouts.
💼 Career
Understanding React context and Next.js layouts is essential for building scalable, maintainable web apps with shared state.
Progress0 / 4 steps
1
Create Theme Context
Create a file called ThemeContext.js and inside it, create a React context called ThemeContext with default value { theme: 'light', toggleTheme: () => {} }. Then create a ThemeProvider component that uses useState to hold theme state initialized to 'light' and a toggleTheme function that switches theme between 'light' and 'dark'. The provider should pass { theme, toggleTheme } as the context value.
NextJS
Hint
Use createContext to make the context. Use useState to hold the theme. Provide theme and toggleTheme in the context value.
2
Wrap Root Layout with ThemeProvider
In the root layout file app/layout.js, import ThemeProvider from ThemeContext.js. Wrap the children inside <ThemeProvider> so the theme context is available throughout the app.
NextJS
Hint
Import ThemeProvider and wrap the children with it in the root layout.
3
Use Theme Context in Main Layout
In app/main/layout.js, import useContext from React and ThemeContext from ThemeContext.js. Use const { theme, toggleTheme } = useContext(ThemeContext) to get the theme state and toggle function. Render a <div> that shows the current theme in a <p> and a <button> that calls toggleTheme on click with text Toggle Theme.
NextJS
Hint
Use useContext(ThemeContext) to get theme and toggleTheme. Show them in JSX with a paragraph and a button.
4
Use Theme Context in Dashboard Layout
In app/dashboard/layout.js, import useContext from React and ThemeContext from ThemeContext.js. Use const { theme } = useContext(ThemeContext) to get the current theme. Render a <div> that displays Dashboard theme: {theme} in a <h2> and includes {children} below it.
NextJS
Hint
Use useContext(ThemeContext) to get theme. Show it in an <h2> inside the dashboard layout.
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
Step 1: Understand the purpose of shared state
Shared state means multiple parts of the app can use the same data without duplication.
Step 2: Identify the benefit in Next.js layouts
Sharing state across layouts lets pages and layouts access common data easily, improving consistency.
Final Answer:
It allows multiple layouts and pages to access the same data easily. -> Option A
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
Step 1: Recall React Context usage
React Context requires wrapping components with a Provider to share state.
Step 2: Apply to Next.js layouts
Wrapping the root layout with the Provider shares state across all nested layouts and pages.
Final Answer:
Wrap the root layout with a Context Provider component. -> Option B
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?
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
Step 1: Understand context sharing
The CountProvider shares count state via context to all nested components.
Step 2: Analyze button behavior
Clicking the button calls setCount to increase count, updating all components using the context.
Final Answer:
Clicking the button increases the count visible in all layouts sharing the context. -> Option A
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
Step 1: Check how nested layouts access context
Nested layouts must use React.useContext or a custom hook to read shared state.
Step 2: Identify common mistake
Forgetting to call useContext means no access to the shared data, even if Provider is correct.
Final Answer:
You forgot to use the custom hook or React.useContext inside nested layouts. -> Option C
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
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.
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.
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.
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
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 unknownstrongwhile earning +1 Grip toward your certificate.