ADVERTISEMENT
Google AdSense Slot (headerLeaderboard)

Set your Publisher ID in src/config/ads.ts to display live ads.

React.js Tutorial• 7 min read

Building Custom React Hooks

Extracting and reusing stateful component logic (useLocalStorage, useWindowSize)

Custom Hooks allow you to extract component logic into reusable JavaScript functions. Custom hook names MUST begin with use (e.g. useWindowSize, useFetch).

The Power of Custom Hooks

Custom hooks can call other React hooks (useState, useEffect, useRef).

Encapsulates complex lifecycle logic (event listeners, storage synchronization, API polling).

Each component calling a custom hook gets completely isolated, independent state.

Creating a useLocalStorage Custom Hook
function useLocalStorage(key, initialValue) {
  const [storedValue, setStoredValue] = React.useState(() => {
    try {
      const item = window.localStorage.getItem(key);
      return item ? JSON.parse(item) : initialValue;
    } catch (error) {
      return initialValue;
    }
  });

  const setValue = (value) => {
    try {
      const valueToStore = value instanceof Function ? value(storedValue) : value;
      setStoredValue(valueToStore);
      window.localStorage.setItem(key, JSON.stringify(valueToStore));
    } catch (error) {
      console.error(error);
    }
  };

  return [storedValue, setValue];
}

// Consuming in any component:
function ThemeSwitcher() {
  const [theme, setTheme] = useLocalStorage("site_theme", "light");
  return (
    <button onClick={() => setTheme(theme === "light" ? "dark" : "light")}>
      Toggle Theme: {theme}
    </button>
  );
}
ADVERTISEMENT
Google AdSense Slot (inContentBanner)

Set your Publisher ID in src/config/ads.ts to display live ads.

Test Yourself With Exercise

+15 XP

What naming convention MUST all custom React hooks strictly follow?