How to Write a Custom Hook in React
Pulling reusable logic out of components into your own hook.
When building React components you'll notice the same few lines of hook logic
showing up in more than one place, like reading a value from localStorage and
saving it back whenever it changes. Instead of copying it into every component,
you can move it into a custom hook.
A custom hook is a function whose name starts with use and that calls other
hooks.
The Repeated Logic
Here's a component that remembers a theme setting in localStorage:
import React, { useState, useEffect } from "react"function Settings() {const [theme, setTheme] = useState(() => localStorage.getItem("theme") || "light")useEffect(() => {localStorage.setItem("theme", theme)}, [theme])return (<select value={theme} onChange={(e) => setTheme(e.target.value)}><option value="light">Light</option><option value="dark">Dark</option></select>)}
useState holds the value and useEffect saves it
whenever it changes. If another component needs to remember a font size or a
sidebar setting, it would need the same code all over again.
Building useLocalStorage
Move that logic into its own function and return the same thing useState does:
// hooks/useLocalStorage.jsimport { useState, useEffect } from "react"export function useLocalStorage(key, initialValue) {const [value, setValue] = useState(() => {const saved = localStorage.getItem(key)return saved !== null ? JSON.parse(saved) : initialValue})useEffect(() => {localStorage.setItem(key, JSON.stringify(value))}, [key, value])return [value, setValue]}
Passing a function to useState means localStorage is only read once, on the
first render. JSON.stringify and JSON.parse let it store numbers, arrays and
objects, not only strings.
Using the Hook
Now any component can use it just like useState:
import React from "react"import { useLocalStorage } from "./hooks/useLocalStorage"function Settings() {const [theme, setTheme] = useLocalStorage("theme", "light")const [fontSize, setFontSize] = useLocalStorage("fontSize", 16)return (<div><select value={theme} onChange={(e) => setTheme(e.target.value)}><option value="light">Light</option><option value="dark">Dark</option></select><button onClick={() => setFontSize(fontSize + 1)}>Font size: {fontSize}</button></div>)}
Two settings, both saved, and the component doesn't know anything about
localStorage.
A Few Rules
- Start the name with
use. React's lint rules use it to check that hooks are called correclty. - Call hooks at the top level of your custom hook, never inside a loop or an
if. - Each component that calls the hook gets its own state. Two components using
useLocalStorage("theme")don't share auseState, they only read and write the same key.
If you find yourself copying a useState and a useEffect between components,
that's a good sign it wants to be a custom hook.
Have some feedback on this post? .