• Stars
    star
    109
  • Rank 319,077 (Top 7 %)
  • Language
    TypeScript
  • License
    MIT License
  • Created almost 4 years ago
  • Updated over 1 year ago

Reviews

There are no reviews yet. Be the first to send feedback to the community and the maintainers!

Repository Details

A flexible React Hook for using Local Storage.

useLocalStorage React hook

A flexible React Hook for using Local Storage.

Test Status Codecov Status


useLocalStorage React hook demo


Features

βœ… Persists data to local storage with an interface similar to the React useState hook

βœ… Works with any hooks-compatible React version

βœ… Works with SSR

βœ… Syncs data between components in the same or different browser tabs

Installation

Install with npm

npm i use-local-storage

Install with yarn

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 provde 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, moreover setting the variable username to undefined will remove it from Local Storage.

import useLocalStorage from "use-local-storage";

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

  return (
    <>
      <input
        value={username}
        onChange={(e) => {
          setUsername(e.target.value);
        }}
      />
      <button
        onClick={() => {
          setUsername(undefined);
        }}
      >
        Remove Username
      </button>
    </>
  );
}

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:

import useLocalStorage from "use-local-storage";

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

  return (
    <>
      <input
        value={username}
        onChange={(e) => {
          setUsername(e.target.value);
        }}
      />
      <button
        onClick={() => {
          setUsername(undefined);
        }}
      >
        Remove Username
      </button>
    </>
  );
}

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. You can also disable the cross-context synchronization by setting syncData to false.

const options = {
  serializer: (obj) => {
    /* Serialize logic */
    return someString;
  },
  parser: (str) => {
    /* Parse logic */
    return parsedObject;
  },
  logger: (error) => {
    // Do some logging
  },
  syncData: false, // You can disable cross context sync
};

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

Attribution

Storage icon made by DinosoftLabs from www.flaticon.com

More Repositories

1

100-days-of-code-frontend

Curriculum for learning front-end development during #100DaysOfCode.
2,628
star
2

interview-guide

An opinionated, actionable guide for software engineering interviews.
Astro
2,430
star
3

javascript-tips-and-tidbits

A continuously-evolving compendium of javascript tips based on common areas of confusion or misunderstanding.
1,193
star
4

typeofnan-javascript-quizzes

JavaScript quiz questions and explanations!
JavaScript
657
star
5

javascript-patterns

A collection of javascript algorithms, patterns, and techniques
JavaScript
292
star
6

random-word-slugs

A handy utility to create those random word slugs (e.g., generous-pink-biscuit) you see all over the place.
TypeScript
54
star
7

react-typescript-todo-app

App created in the React TypeScript Todo App tutorial
TypeScript
40
star
8

ts-redux

Sample React Redux Typescript app with thunks
TypeScript
34
star
9

roll-your-own

Learn built-in JavaScript methods by rolling your own!
JavaScript
27
star
10

combinate

Combinatorics generator for JavaScript and Typescript.
TypeScript
25
star
11

diy-node-router

A node-based router that emulates the Express.js router
JavaScript
18
star
12

dev-blogs

Continuously updated list of blog posts by top developers.
15
star
13

express-typescript-app

An app accompanying the express/typescript tutorial blog post
TypeScript
13
star
14

usecontext-theme-toggling

This is a simple example repository demonstrating one way to toggle React themes using the useContext hook.
HTML
13
star
15

imdb-data

A JSON file of 50,000 IMDB movie reviews to be used in machine learning applications.
JavaScript
12
star
16

neon-glow-theme

A dark neon theme that will make your code glow
11
star
17

typeofnan-javascript-reference

JavaScript reference demonstrating concepts line-by-line
JavaScript
8
star
18

svelte-dark

7
star
19

react-bootstrap-album-template

The Bootstrap 4 Album Template using React / Reactstrap.
JavaScript
7
star
20

react-mirror

React-based magic mirror with node/express back-end.
JavaScript
6
star
21

docker-examples

Practice with docker
HTML
6
star
22

react-redux-typescript-starter

TypeScript
5
star
23

use-effect-debounced

A custom React hook that provides a debounced version of useEffect.
HTML
5
star
24

code-screenshots

JavaScript
4
star
25

grid-search

A small, simple node module that can be used to generate an array of parameters to use during a machine learning grid search
JavaScript
4
star
26

pgn-converter

A simple python script to convert PGN files between LiChess and ChessBase formats
Python
3
star
27

use-context-react-typescript

Basic auth example with useContext in React/typescript
TypeScript
3
star
28

semantic-validation

Semantic validation for javascript objects.
JavaScript
3
star
29

js-object-schema-migration

An approach to JavaScript object schema migration.
JavaScript
3
star
30

and-or

Easy javascript logic tests
JavaScript
3
star
31

noble-tech

A list of companies with noble missions
3
star
32

fun-with-react-and-git-hooks

Adding git hooks to a React project to make sure testing and linting are performed before git commits/pushes.
JavaScript
3
star
33

react-getting-started-generator

A demo of using JavaScript generators with React to progress through a Getting Started guide.
HTML
2
star
34

how-the-web-works

Short and clear explanations about how the web works. Each article will focus on one piece of tech (or concept) and explain it in a way anyone could understand.
2
star
35

gatsby-starter-netlify-cms

JavaScript
2
star
36

chess-focus-extension

Small chrome extension made for a friend to focus on certain types of lichess games
JavaScript
2
star
37

redux-debounce-middleware

An approach to debouncing in Redux using middleware.
JavaScript
2
star
38

tensorflow-webworker

Configuring basic tensorflow functionality in a web worker, bundled using webpack
JavaScript
2
star
39

train-test-split

Split your dataset into training and test datasets.
JavaScript
2
star
40

nas5w

1
star
41

selector

JavaScript
1
star
42

kirby

Node-base static HTML blog generator (in development)
JavaScript
1
star
43

use-debounce

JavaScript
1
star
44

google-analytics-predictions

R
1
star
45

stackbot

JavaScript
1
star
46

rtl-testing-demo

Code that accompanies the blog post, "How to Test Your React App Effectively with React Testing Library"
TypeScript
1
star
47

newscloud

Aurelia/Node.js app to retrieve google news on a topic and display associated words in a wordcloud.
JavaScript
1
star
48

react-query-test

JavaScript
1
star
49

derived-state-using-selectors

Calculating derived state in JavaScript using composable selectors.
JavaScript
1
star
50

costa-rican-poverty-prediction

R
1
star
51

checksy-react

JavaScript
1
star
52

cf-stackbot

JavaScript
1
star