Consider two sibling components in Next.js using useState independently. What happens when one updates its state?
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>; }
Think about how useState works inside each component instance.
Each useState call creates independent state local to that component instance. Sibling components do not share state unless explicitly connected.
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?
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} />
Consider how useEffect updates state when props change.
The initial state is set to the first prop value (5). When the prop changes to 10, useEffect updates the local state, causing the component to display 10.
Examine the code below. Why does it cause infinite re-renders?
import React, { useState, useEffect } from 'react'; function Timer() { const [seconds, setSeconds] = useState(0); useEffect(() => { setSeconds(seconds + 1); }, [seconds]); return <div>{seconds}</div>; }
Think about what triggers useEffect and what happens inside it.
The effect depends on seconds. Inside the effect, setSeconds updates seconds, causing the effect to run again. This loop causes infinite re-renders.
You want to keep a piece of state synchronized between server-rendered content and client interactions in Next.js. Which approach is best?
Think about how Next.js handles server and client rendering.
React Server Components fetch data on the server and pass it down as props. Client components can then use local state for interactions, keeping server and client in sync.
Choose the correct code snippet that creates a React Context to share a counter state and updater across components.
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); }
Remember the context value should provide both state and updater to consumers.
Option C correctly creates a context, provides both count and setCount in the value, and defines a hook to consume the context.
Other options either provide only count or only setCount or a fixed value, which breaks shared state updates.