Skip to main content
InterviewHubPRO
Section Overview
Q312

Question 312 of 407

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

77%
React Core & Hooks (407 Qs)•Part 9: React Hooks Deep Dive (262 - 316)

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

mid LevelMost AskedCode ExampleComponentsHooks

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 FontSizeController() {
  const [size, setSize] = useLocalStorage('preferred_font_size', 16);
  return (
    <div>
      <span>Font Size: {size}px</span>
      <button onClick={() => setSize((s) => s + 2)}>+</button>
      <button onClick={() => setSize((s) => Math.max(12, s - 2))}>-</button>
    </div>
  );
}