DEV Community

Cover image for Building a Simple React Custom Hook
Gonçalo Alves
Gonçalo Alves

Posted on

Building a Simple React Custom Hook

Have you ever had the need to persist certain bits of your app’s state, even after a dreaded page refresh? Have you ever wished for an alternative to backend storage for small amounts of data? Don't worry, we've all been there.

Let's use React Custom Hooks to do that exactly.

As a React developer, one constant feature I've always wanted is to be able to store and retrieve user data right from my application, without making an extra round trip to the server or managing a database. I've explored different solutions, but found myself frequently circling back to the underrated localStorage API. However, directly using this API comes with figuring out where, when and how to handle its operations.

Then one day, some kind of magic happened. I stumbled upon React hooks and, boy oh boy, did that make a difference. Suddenly I was able to extract my localStorage handling code into its dedicated area, creating a custom hook that simplified my codebase to unprecedented levels.

Let me walk you through it.

import { useState, useEffect } from "react";

const useLocalStorage = (key, initialValue) => {
    const [storedValue, setStoredValue] = useState(() => {
        try {
            const item = window.localStorage.getItem(key);
            return item ? JSON.parse(item) : initialValue;
        } catch (error) {
            console.log(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.log(error);
        }
    };

    return [storedValue, setValue];
};

export default useLocalStorage;
Enter fullscreen mode Exit fullscreen mode

Just like that, you have created your custom hook to handle localStorage. What you are seeing here is a beautifully layered piece of code. It takes a key and initial value as parameters. In return, it gets a state variable and setter function to update that value.

Excited about how to use this freshly baked hook? Let me show you:

import useLocalStorage from './useLocalStorage';

function App() {
    const [name, setName] = useLocalStorage('name', '');

    return (
        <div>
            <input
                type='text'
                value={name}
                onChange={e => setName(e.target.value)}
            />
        </div>
    );
}

export default App;
Enter fullscreen mode Exit fullscreen mode

There you go! Now, each time you type in the input box in your App component, it will automatically store your changes to localStorage under the key "name". Not only that, but it won't forget even if you refresh, restart, or come back to it after an hour-long coffee break.

Life as a React developer just got easier! With hooks, especially custom hooks like this, we now have delightful, reusable pieces of code that preserve the beautiful, declarative nature of React we all cherish.

So why not dish out your favourite text editor, roll up your sleeves, and start experimenting with this brand new custom hook right now? Just like me, I'm sure you'll discover joy and practical efficiency in this exciting React feature. Happy coding!

Connect with me

If you like this article be sure to leave a comment. That will make my day!

If you want to read other stuff by me you can check out my personal blog.

If you want to connect with me you can send me a message on Twitter/X.

You can also check other stuff that I have going on here

Top comments (0)