Ch. 3 · React

React Custom Hooks and Shared Logic

React Custom Hooks and Shared Logic. Learn the reasoning, a practical example, common mistakes and an interview exercise.

~2 min readintermediateupdated Oct 3, 2026

Custom hooks share logic, not a single state instance. Each call has its own hook state unless it deliberately connects to shared external storage.

Before you start

You should know how a function component renders JSX, receives props and handles events. Follow the value through render, interaction and the next render. Small snippets below belong inside an existing React application unless they are explicitly shown as complete components.

The practical goal is to reason through this situation: Two components calling a local counter hook receive independent counts. Read the walkthrough first, then try the interview exercise before opening its answer. The important part is explaining the decision and its consequences, rather than remembering a definition alone.

Step-by-step walkthrough

Step 1: State the hook’s contract

Decide whether each caller owns a local value or subscribes to one shared source. The name alone cannot establish sharing.

Step 2: Trace two calls

Call the hook in A and B. If it uses local useState, an update in A changes only A’s instance.

Step 3: Choose a shared owner

Lift state above both callers or connect to context or an external store. Preserve a clear subscription and update contract.

Worked scenario

Two components calling a local counter hook receive independent counts.

function useCounter() {
  const [count, setCount] = useState(0);
  return [count, () => setCount(value => value + 1)];
}
JSX

Import useState. Calling useCounter twice creates two independent hook state sequences. Extracting code into a hook removes duplication; it does not merge state ownership across components.

Common mistake

Naming a function useSomething does not make module variables reactive.

Verify the behavior

Render two counters and click one. For a shared variant, confirm both change and that unmounting one does not destroy the remaining owner’s state.

Interview exercise

Share one counter across components.

Answer and reasoning

Lift state to a common owner, use context, or subscribe to an external store with a clear update contract.

Continue learning

Compare the scenario with the React interview questions and test your understanding with the React MCQs. For terminology and implementation details, consult the reference material.

More in React

read ✓React · hard

React Context Splitting for Performance

Stop a single context value from re-rendering every consumer by splitting state and dispatch and memoizing the provider value.

~2 min readread →
read ✓React · mid

React lazy Loading and Code Splitting

Split bundles with lazy and Suspense, work with default exports, and place boundaries so a chunk loads only when needed.

~2 min readread →
esc