Build a useLocalStorage React Hook Package (Contribute to Open Source with Me)
Tags: react, javascript, typescript, webdev
Published: 2021-01-11 08:58:33

---
title: Build a useLocalStorage React Hook Package (Contribute to Open Source with Me)
published: true
description: I have been dogfooding a useLocalStorage React hook for a while and just yesterday open-sourced it on npm as the uselocalstorage package. I'm looking for help!
tags: react, javascript, typescript, webdev
cover_image: https://dev-to-uploads.s3.amazonaws.com/i/px0goyt3vcbagv1frx4o.png
---

I have been dogfooding a `useLocalStorage` React hook for a while and just yesterday open-sourced it on npm as the [`uselocalstorage` package](https://www.npmjs.com/package/use-local-storage).

Do you have an interest in contributing to open source? If so, I'm looking for help, regardless of your level of experience!

**First time contributors welcome!**

**If you’re interested, be sure to [follow the GitHub repo here](https://github.com/nas5w/use-local-storage/stargazers) and check out the open issues.**

<hr />

## Please give this post a 💓, 🦄, and 🔖 to help grow the effort!

<hr />

# About the Hook

The `useLocalStorage` hook acts a lot like the `useState` hook, except it also persists your stateful data to your browser's local storage. The hook is available in JavaScript and Typescript.

# Yes, There are Alternatives!

I am well aware that there are alternatives, even good alternatives, to this package! That being said, I also believe that more attempts to build something can only be better as competition allows the best solutions to rise to the top.

# Help I'm Looking For

I have started outlining the various tasks I'm looking for help with in the [Github Issues Page](https://github.com/nas5w/use-local-storage/issues). Here's what I have so far:

- Add `CONTRIBUTING.md`
- Add `CODE_OF_CONDUCT.md`
- Prevent sync issues in different tabs by using a `"storage"` window event listener.
- Use the hook and suggest more features!

Note that some of these probably require some React/Typescript experience, but others are administrative help that's just as important and anyone can help with!

# Installation

Install with npm

```bash
npm i use-local-storage
```

Install with yarn

```bash
yarn add use-local-storage
```

# Basic Usage

In its most basic form, the `useLocalStorage` hook just needs the Local Storage `key` you wish to use. However, it's advised that you also provide a default value as a second argument in the event that they `key` does not yet exist in Local Storage.

The following usage will persist the `username` variable in a `"name"` key in Local Storage. It will have a default/initial value of an empty string `""`. This default value will _only_ be used if there is no value already in Local Storage.

```jsx
import useLocalStorage from "use-local-storage";

function MyComponent() {
  const [username, setUsername] = useLocalStorage("name", "");

  return (
    <>
      <input
        value={username}
        onChange={(e) => {
          setUsername(e.target.value);
        }}
      />
    </>
  );
}
```

**Note:** By default, the `useLocalStorage` hook uses `JSON.stringify` and `JSON.parse` to serialize and parse the data, respectively. A custom serializer and/or parser can be configured if desired (discussed below in the Advanced Usage section).

## Typescript Use

The type of `username` will be inferred from your default value. In this case, the type of `string` will be inferred.

If you use `useLocalStorage` _without_ providing a default value, or you simply want to specify that `username` is actually of a different type, you should pass the type of your data as a generic:

```tsx
import useLocalStorage from "use-local-storage";

function MyComponent() {
  const [username, setUsername] = useLocalStorage<string>("name");

  return (
    <>
      <input
        value={username}
        onChange={(e) => {
          setUsername(e.target.value);
        }}
      />
    </>
  );
}
```

# Advanced Usage / Options

the `useLocalStorage` hook takes an optional third `options` argument. This allows you to configure a custom serializer and/or parser if you need to use something other than `JSON.stringify` and `JSON.parse`. The `options` object also has a `logger` key to log an errors caught in the hook.

```javascript
const options = {
  serializer: (obj) => {
    /* Serialize logic */
    return someString;
  },
  parser: (str) => {
    /* Parse logic */
    return parsedObject;
  },
  logger: (error) => {
    // Do some logging
  },
};

const [data, setData] = useLocalStorage("data", { foo: "bar" }, options);
```

# Attribution

<div>Storage icon made by <a href="https://www.flaticon.com/authors/dinosoftlabs" title="DinosoftLabs">DinosoftLabs</a> from <a href="https://www.flaticon.com/" title="Flaticon">www.flaticon.com</a></div>