React’s useState and useEffect hooks are essential for managing dynamic data and side-effects. But sometimes, we want to extract complex logic into a reusable function. That’s where custom hooks come in — allowing us to encapsulate behavior and reuse it across components.
The goal of this custom hook is to synchronize a component’s state with localStorage. It works just like useState but also reads and writes to the browser’s storage:
const useStorageState = (key, initialState) => {
const [value, setValue] = React.useState(
localStorage.getItem(key) || initialState
);
React.useEffect(() => {
localStorage.setItem(key, value);
}, [value, key]);
return [value, setValue];
};In your component, you can use it like this:
const [searchTerm, setSearchTerm] = useStorageState('search', 'React');This gives you a state variable and an updater function, just like useState, but with built-in persistence.
use to follow React’s conventions.value instead of domain-specific ones.Custom hooks in React are a powerful way to abstract and reuse logic. With useStorageState, we’ve created a hook that keeps state in sync with localStorage, improving user experience and code maintainability. These patterns are essential for building scalable and professional React applications.