React Medium technical 1 views 1 min read

How do you share state logic between components using custom hooks?

Peer-reviewed by HireXTech Technical Panel • Updated for 2025/2026 hiring • Editorial standards
Practise this track
Interviewer Expectations for this Question
01
Core Competency

Assesses fundamental understanding of React conventions, runtime behavior, and memory/performance considerations.

02
Evaluation Criteria

Hiring managers look for precision, avoidance of ambiguous jargon, and ability to explain trade-offs under real production conditions.

Comprehensive Model Answer Verified Solution

Custom hooks allow you to extract and share stateful logic between components without changing their hierarchy. The state itself is not shared—each component using the hook gets its own isolated state.

#### Example: useLocalStorage Hook

     import { useState, useEffect } from 'react';

     function useLocalStorage(key, initialValue) {
       // Get stored value or use initial value
       const [storedValue, setStoredValue] = useState(() => {
         try {
           const item = window.localStorage.getItem(key);
           return item ? JSON.parse(item) : initialValue;
         } catch (error) {
           console.error(error);
           return initialValue;
         }
       });

       // Update localStorage when state changes
       useEffect(() => {
         try {
           window.localStorage.setItem(key, JSON.stringify(storedValue));
         } catch (error) {
           console.error(error);
         }
       }, [key, storedValue]);

       return [storedValue, setStoredValue];
     }

     // Usage in multiple components
     function ThemeToggle() {
       const [theme, setTheme] = useLocalStorage('theme', 'light');
       return (
         <button onClick={() => setTheme(theme === 'light' ? 'dark' : 'light')}>
           Current: {theme}
         </button>
       );
     }

     function FontSizeSelector() {
       const [fontSize, setFontSize] = useLocalStorage('fontSize', 16);
       return (
         <input 
           type="range" 
           value={fontSize} 
           onChange={(e) => setFontSize(Number(e.target.value))} 
         />
       );
     }
     

Both components use useLocalStorage, but each has its own independent state that persists to localStorage.

Candidate Response Strategy & Interview Tips

  1. Start with a concise one-sentence summary: Deliver a direct, confident answer first before expanding into nuances.
  2. Demonstrate real-world trade-offs: Discuss where this approach excels and when you would avoid it in production systems.
  3. Discuss complexity & edge cases: Proactively explain time/space complexity or boundary conditions (null values, scale limits).
  4. Prepare for interviewer follow-ups: Technical hiring panels frequently probe deeper into concurrency, backward compatibility, or alternative libraries.
Spotted an error or have an alternative solution?