InterviewHubPRO
Section Overview
Q312

Question 312 of 445

Part 9: React Hooks Deep Dive (262 - 316)

70%
React & Modern Frontend (445 Qs)•Part 9: React Hooks Deep Dive (262 - 316)

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

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

jsx
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.