Hello! Let's get started with our third lesson on custom hooks.
In our last session, we delved into the "Rules of Hooks." We established that React's ability to manage state relies on a consistent call order, which led us to the two fundamental rules: only call hooks at the top level and only from React functions. These rules aren't just constraints; they are the very foundation that allows us to build our own powerful, reusable hooks.
Today, we'll put that foundational knowledge into practice. We're moving from the "why" to the "what" by building our first truly flexible custom hook. Our goal is to create a generic custom hook with TypeScript to encapsulate reusable stateful logic. You'll learn how to write a hook that isn't just reusable in one project, but can handle different data types (string, array, object) with full type safety.
The Problem: Duplicated Stateful Logic
Imagine you're building an application. You have a toggle for a dark/light theme, and you also have a list of to-do items. A common requirement is to save both the theme preference and the to-do list to the browser's localStorage. This way, when the user refreshes the page, their settings and data are still there.
How would you implement this? For each piece of state, you would likely use:
- A
useStatehook to hold the value in the component. - A
useEffecthook to read the initial value fromlocalStoragewhen the component first mounts. - Another
useEffecthook to write the value back tolocalStoragewhenever it changes.
If you do this for both the theme (string) and the to-do list (Item[]), you'll quickly find yourself with nearly identical blocks of code in different parts of your application. This duplication violates the DRY (Don't Repeat Yourself) principle and makes the code harder to maintain.
This video provides an excellent walkthrough of this exact problem.
Custom Hooks in React - Every React Developer Should Know This
To see this problem in action, watch the first part of the video 'Custom Hooks in React' from ByteGrad. It clearly demonstrates how the logic for persisting state to local storage gets duplicated.
Watch from 06:15 to 11:29. The video sets up two pieces of state—items and theme—and shows how the useState and useEffect logic to sync them with localStorage is essentially the same for both.
The Solution: Extracting Logic into a Custom Hook
As the video highlighted, when you have duplicated logic that involves React hooks (useState, useEffect), you shouldn't create a simple utility function. You need to create a custom hook.
The process is straightforward:
- Create a new function with a name that starts with
use(e.g.,useLocalStorage). - Copy one of the duplicated logic blocks into this new function.
- Identify what makes the logic specific (in this case, the
localStoragekey and the initial value) and turn those into function parameters. - Return the state and the setter function from your hook, just like
useStatedoes.
Let's see this process in action.
Custom Hooks in React - Every React Developer Should Know This
The next segment of the same video shows exactly how to refactor the duplicated code into a reusable useLocalStorage hook.
Continue watching from 11:29 to 15:03. Focus on how the theme logic is extracted and then generalized by introducing a key parameter. This transforms specific logic into a reusable utility.
Now, instead of dozens of lines of code for each piece of persistent state, you have a clean, one-line call:
// Before
const [theme, setTheme] = useState(() => { /* ... localStorage logic ... */ });
useEffect(() => { /* ... localStorage logic ... */ }, [theme]);
// After
const [theme, setTheme] = useLocalStorage('theme', 'light');
This is a huge improvement in readability and maintainability! But there's a problem lurking... How does TypeScript know the type of theme?
Making the Hook Generic with TypeScript
Our useLocalStorage hook needs to handle a string for the theme, an Item[] for a list, or maybe a UserSettings object. If we're not careful, we might be tempted to use the any type, which would sacrifice all the benefits of TypeScript.
The correct solution is to use generics. You've likely encountered generics in your computer science studies; they allow us to write functions or classes that can operate on a variety of types while maintaining strict type checking. In TypeScript, we denote a generic type parameter with angle brackets, like <T>.
Let's see how to apply this to our custom hook to make it truly generic and type-safe.
Custom Hooks in React - Every React Developer Should Know This
This is the most crucial part of the lesson. The video now explains how to introduce a generic type parameter <T> to the useLocalStorage hook, making it fully type-safe for any data type.
Watch from 20:10 to 26:25. Pay close attention to how <T> is introduced in the function signature function useLocalStorage<T>(...). Notice how T is then used to type the initialValue, the state itself, and the return value. This creates a relationship between the input type and the output type, which is the essence of generics.
This textual resource provides a great summary of the concepts you just saw in the video.
Advanced TypeScript Generics in React Hooks
The article 'Advanced TypeScript Generics in React Hooks' provides a solid written explanation of how generics work in the context of custom hooks.
Read the sections 'Understanding the basics of TypeScript Generics', 'Implementing TypeScript Generics in React Hooks', and the FAQ answer for 'How are TypeScript generics used in React hooks?'. This will reinforce your understanding of the syntax and purpose of generics.
The Final useLocalStorage Hook
Let's consolidate what we've learned into the final, complete code for our generic useLocalStorage hook.
// src/hooks/useLocalStorage.ts
import { useState, useEffect } from 'react';
// The function signature includes <T> to declare it as a generic function.
// T will be a placeholder for whatever type the caller provides.
function useLocalStorage<T>(key: string, initialValue: T): [T, React.Dispatch<React.SetStateAction<T>>] {
// The state is initialized with a function to ensure this complex logic
// only runs once on the initial render.
const [value, setValue] = useState<T>(() => {
try {
const item = window.localStorage.getItem(key);
// If an item exists in localStorage, parse it.
// Otherwise, return the provided initialValue.
return item ? JSON.parse(item) : initialValue;
} catch (error) {
console.error(error);
return initialValue;
}
});
// This effect runs whenever the `key` or `value` changes.
useEffect(() => {
try {
// Save the current value to localStorage.
window.localStorage.setItem(key, JSON.stringify(value));
} catch (error) {
console.error(error);
}
}, [key, value]);
// The hook returns a tuple [value, setValue], mirroring the useState API.
// TypeScript correctly types `value` as `T` and `setValue` as the setter for `T`.
return [value, setValue];
}
export default useLocalStorage;
How to Use It:
// In your component
import useLocalStorage from './hooks/useLocalStorage';
interface Todo {
id: number;
text: string;
completed: boolean;
}
function App() {
// Here, TypeScript infers T as `string` because 'light' is a string.
// `theme` is type `string`, `setTheme` is `(value: string) => void`.
const [theme, setTheme] = useLocalStorage('theme', 'light');
// Here, TypeScript infers T as `Todo[]` because the initial value is an empty array.
// We explicitly tell it the array type for better type safety.
// `todos` is type `Todo[]`, `setTodos` is `(value: Todo[]) => void`.
const [todos, setTodos] = useLocalStorage<Todo[]>('todos', []);
// ...
}
Notice how we get full type safety and autocompletion, all from one reusable hook!
Test your understanding!
You want to create a simple useToggle hook that manages a boolean state. The desired usage is: const [isOn, toggle] = useToggle(false);.
Write the implementation for this useToggle custom hook. It should take an initial boolean value and return an array containing the current state and a function to toggle it.
Show answer
The implementation is a great example of a simple stateful hook.
import { useState, useCallback } from 'react';
// The hook takes an initial boolean value.
function useToggle(initialState: boolean = false): [boolean, () => void] {
// Use useState to store the boolean state.
const [state, setState] = useState<boolean>(initialState);
// Define the toggle function.
// We use useCallback to ensure the function reference is stable between renders,
// unless its dependencies change (none in this case). This is an optimization.
const toggle = useCallback(() => {
setState(prevState => !prevState);
}, []);
// Return the state and the toggle function in a tuple.
return [state, toggle];
}
export default useToggle;
This encapsulates the logic of "toggling a boolean" into a clean, reusable hook.
Another Powerful Example: A Generic useForm Hook
The power of generic custom hooks extends far beyond localStorage. Another extremely common use case is managing form state. This resource shows how to build a generic useForm hook that can handle any form structure.
Mastering React Hooks: useEffect, useReducer, and ...
The article 'Mastering React Hooks' provides an excellent, practical example of another generic custom hook: useForm.
Read the sections 'Example: useForm Hook' and 'Using useForm in a Component'. Notice how the generic type <T> allows the hook to adapt to a SignupForm with completely different fields, simply by changing the initialValues object passed to it. This demonstrates the incredible flexibility of this pattern.
The useForm hook is a perfect illustration of how custom hooks can dramatically clean up your components by abstracting away the boilerplate logic of handling input changes and state updates.
Conclusion
Today you've made a significant leap from being a user of hooks to a creator of them. By combining the Rules of Hooks with the power of TypeScript generics, you can now build your own stateful logic that is clean, reusable, and type-safe.
Key Takeaways:
- Identify Duplication: Custom hooks are the answer when you find yourself repeating stateful logic (involving
useState,useEffect, etc.) across components. - Extract and Generalize: Move the duplicated logic into a function named with a
useprefix. Turn the specific parts of the logic into parameters. - Embrace Generics for Type Safety: Use a generic type parameter
<T>to allow your hook to work with multiple data types without sacrificing type safety. - TypeScript Infers Types: When you call a generic hook, TypeScript will usually infer the type
Tfrom the initial values you provide, giving you a seamless development experience.
Preview of the Next Lesson:
One of the most common pieces of stateful logic to extract is data fetching. In our next lesson, we will focus on building a dedicated custom hook for this purpose. You will extract data fetching, loading, and error handling logic into a custom useFetch hook, which is a staple in almost every React application.