Tobias S
Tobio's Blog

Tobio's Blog

A hook for localStorage - store stuff in the user's browser memory!

I'm writing a sort of game using React. It's supposed to be used in the classroom, to help kids remember flashcards.

I'm in the process of writing code that allows the user to add their own images to the game. To begin with, I'll use local storage - I'll probably use FireStore later on.

Here's a hook I wrote to use local storage.

function useLocalStorage(keyname: string) {
  const storeImages = (images: string[]) => {
    window.localStorage.setItem(
      keyname,
      JSON.stringify({ userImages: images })
    );
  };

  const retrieveImages = () => {
    const dat = window.localStorage.getItem(keyname);
    if (dat) {
      return JSON.parse(dat).userImages;
    }
  };
  return { storeImages, retrieveImages };
}
export default useLocalStorage;

I'm sharing it mainly because I think it'll be useful, but also because I'm quite new to writing custom hooks and I think this is a pretty good example of one for a first try - simple, actually useful, and it returns functions, which is more exciting to try than returning a boolean or some other data!

 
Share this