Bird
Raised Fist0
NextJSframework~20 mins

State synchronization patterns in NextJS - Practice Problems & Coding Challenges

Choose your learning style10 modes available
Challenge - 5 Problems
🎖️
State Sync Master
Get all challenges correct to earn this badge!
Test your skills under time pressure!
❓ component_behavior
intermediate
2:00remaining
How does useState synchronize state across components?

Consider two sibling components in Next.js using useState independently. What happens when one updates its state?

NextJS
import React, { useState } from 'react';

function SiblingA() {
  const [count, setCount] = useState(0);
  return <button onClick={() => setCount(count + 1)}>Increment A: {count}</button>;
}

function SiblingB() {
  const [count, setCount] = useState(0);
  return <button onClick={() => setCount(count + 1)}>Increment B: {count}</button>;
}
AUpdating state in SiblingA does not affect SiblingB's state; they remain independent.
BUpdating state in SiblingA automatically updates SiblingB's state to the same value.
CBoth components share the same state because useState is global in Next.js.
DUpdating state in SiblingA causes a runtime error due to conflicting states.
Attempts:
2 left
💡 Hint

Think about how useState works inside each component instance.

❓ state_output
intermediate
2:00remaining
What is the output when syncing state with useEffect and props?

Given a Next.js component receiving a count prop and syncing it to local state with useEffect, what will be the displayed count after prop changes?

NextJS
import React, { useState, useEffect } from 'react';

function Counter({ count }) {
  const [localCount, setLocalCount] = useState(count);
  useEffect(() => {
    setLocalCount(count);
  }, [count]);
  return <div>{localCount}</div>;
}

// Parent renders <Counter count={5} />, then updates to <Counter count={10} />
AThe component always shows 5, ignoring prop updates.
BThe component first shows 5, then updates to show 10 after prop changes.
CThe component shows 10 immediately without showing 5 first.
DThe component throws an error because state and props conflict.
Attempts:
2 left
💡 Hint

Consider how useEffect updates state when props change.

🔧 Debug
advanced
2:00remaining
Why does this Next.js component cause infinite re-renders?

Examine the code below. Why does it cause infinite re-renders?

NextJS
import React, { useState, useEffect } from 'react';

function Timer() {
  const [seconds, setSeconds] = useState(0);
  useEffect(() => {
    setSeconds(seconds + 1);
  }, [seconds]);
  return <div>{seconds}</div>;
}
ABecause <code>setSeconds</code> inside <code>useEffect</code> updates <code>seconds</code>, triggering <code>useEffect</code> again endlessly.
BBecause <code>seconds</code> is never updated, so the component freezes.
CBecause <code>useEffect</code> is missing a cleanup function causing memory leaks.
DBecause <code>useState</code> is used incorrectly without initial value.
Attempts:
2 left
💡 Hint

Think about what triggers useEffect and what happens inside it.

🧠 Conceptual
advanced
2:00remaining
Which pattern best synchronizes state between server and client in Next.js?

You want to keep a piece of state synchronized between server-rendered content and client interactions in Next.js. Which approach is best?

AUse <code>getStaticProps</code> to fetch data and update state only on the client.
BUse only client-side state with <code>useState</code> and ignore server data.
CUse global variables to share state between server and client.
DUse React Server Components to fetch data on the server and pass it as props to client components with local state.
Attempts:
2 left
💡 Hint

Think about how Next.js handles server and client rendering.

📝 Syntax
expert
3:00remaining
Which option correctly implements a shared state using React Context in Next.js?

Choose the correct code snippet that creates a React Context to share a counter state and updater across components.

NextJS
import React, { createContext, useState, useContext } from 'react';

const CounterContext = createContext();

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

function useCounter() {
  return useContext(CounterContext);
}
A
const CounterContext = React.createContext();

function CounterProvider({ children }) {
  const [count, setCount] = useState(0);
  return &lt;CounterContext.Provider value={count}&gt;{children}&lt;/CounterContext.Provider&gt;;
}

function useCounter() {
  return useContext(CounterContext);
}
B
const CounterContext = React.createContext(0);

function CounterProvider({ children }) {
  const count = 0;
  return &lt;CounterContext.Provider value={count}&gt;{children}&lt;/CounterContext.Provider&gt;;
}

function useCounter() {
  return useContext(CounterContext);
}
C
const CounterContext = React.createContext();

function CounterProvider({ children }) {
  const [count, setCount] = useState(0);
  return &lt;CounterContext.Provider value={{ count, setCount }}&gt;{children}&lt;/CounterContext.Provider&gt;;
}

function useCounter() {
  return useContext(CounterContext);
}
D
const CounterContext = React.createContext();

function CounterProvider({ children }) {
  const [count, setCount] = useState(0);
  return &lt;CounterContext.Provider value={setCount}&gt;{children}&lt;/CounterContext.Provider&gt;;
}

function useCounter() {
  return useContext(CounterContext);
}
Attempts:
2 left
💡 Hint

Remember the context value should provide both state and updater to consumers.

Practice

(1/5)
1. What is the main purpose of state synchronization in Next.js applications?
easy
A. To keep data consistent between server and client components
B. To improve CSS styling performance
C. To handle routing between pages
D. To optimize image loading speed

Solution

  1. Step 1: Understand state synchronization concept

    State synchronization means keeping data the same across different parts of an app, especially between server and client.
  2. Step 2: Identify Next.js usage

    Next.js apps often fetch data on the server and need to keep that data consistent on the client side.
  3. Final Answer:

    To keep data consistent between server and client components -> Option A
  4. Quick Check:

    State sync = consistent data [OK]
Hint: Think about data staying the same everywhere [OK]
Common Mistakes:
  • Confusing state sync with styling or routing
  • Thinking it only applies to client-side
  • Assuming it improves image loading
2. Which of the following is the correct way to update a React state variable count using the useState hook in Next.js?
easy
A. updateCount(count + 1);
B. count = count + 1;
C. useState(count + 1);
D. setCount(count + 1);

Solution

  1. Step 1: Recall useState update syntax

    React's useState returns a setter function to update state, e.g., setCount(newValue).
  2. Step 2: Identify correct usage

    Direct assignment like count = count + 1 is invalid; useState(count + 1) is a hook call, not update; updateCount is undefined.
  3. Final Answer:

    setCount(count + 1); -> Option D
  4. Quick Check:

    useState setter = setCount() [OK]
Hint: Use the setter function from useState to update state [OK]
Common Mistakes:
  • Trying to assign state variable directly
  • Calling useState inside event handlers
  • Using undefined update functions
3. Consider this Next.js component snippet:
import { useState, useEffect } from 'react';

export default function Counter() {
  const [count, setCount] = useState(0);

  useEffect(() => {
    const timer = setInterval(() => {
      setCount(c => c + 1);
    }, 1000);
    return () => clearInterval(timer);
  }, []);

  return <div>Count: {count}</div>;
}

What will the component display after 3 seconds?
medium
A. Count: 0
B. Count: 3
C. Count: 1
D. Count: NaN

Solution

  1. Step 1: Understand useEffect with empty dependency

    The effect runs once on mount, setting an interval that increments count every 1000ms.
  2. Step 2: Calculate count after 3 seconds

    After 3 intervals (3 seconds), count increments from 0 to 3.
  3. Final Answer:

    Count: 3 -> Option B
  4. Quick Check:

    Increment every second = 3 after 3s [OK]
Hint: Count increments once per second, so 3 seconds = 3 [OK]
Common Mistakes:
  • Thinking useEffect runs multiple times
  • Ignoring the cleanup function
  • Assuming count resets
4. You have this Next.js component code that fetches data and sets state:
import { useState, useEffect } from 'react';

export default function DataFetcher() {
  const [data, setData] = useState(null);

  useEffect(() => {
    fetch('/api/data')
      .then(res => res.json())
      .then(json => setData(json));
  }, []);

  return <div>{data.title}</div>;
}

What error might occur when this component first renders?
medium
A. Infinite loop in useEffect
B. SyntaxError in fetch call
C. Cannot read property 'title' of null
D. setData is not a function

Solution

  1. Step 1: Analyze initial state and render

    Initial state data is null, so on first render data.title tries to access property of null.
  2. Step 2: Identify runtime error

    Accessing property on null causes a runtime error: "Cannot read property 'title' of null".
  3. Final Answer:

    Cannot read property 'title' of null -> Option C
  4. Quick Check:

    Access null.title = error [OK]
Hint: Check if state is null before accessing properties [OK]
Common Mistakes:
  • Assuming fetch syntax error
  • Expecting infinite loop without dependencies
  • Confusing setData function availability
5. In Next.js, you want to synchronize server-fetched data with client state and update it on user interaction. Which pattern best achieves this?
hard
A. Fetch data in getServerSideProps, pass as props, then use useState on client to manage updates
B. Fetch data only on client with useEffect and ignore server data
C. Use getStaticProps and never update client state
D. Store data in a global variable outside React components

Solution

  1. Step 1: Understand server and client data flow

    getServerSideProps fetches fresh data on each request, passing it as props to the component.
  2. Step 2: Use client state for updates

    Using useState with initial props allows client-side updates while keeping initial server data.
  3. Final Answer:

    Fetch data in getServerSideProps, pass as props, then use useState on client to manage updates -> Option A
  4. Quick Check:

    Server props + client state = sync and update [OK]
Hint: Combine server props with client useState for sync and updates [OK]
Common Mistakes:
  • Ignoring server data and fetching only on client
  • Using static props without updates
  • Using global variables outside React state
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