Ecosyste.ms: Awesome

An open API service indexing awesome lists of open source software.

Awesome Lists | Featured Topics | Projects

https://github.com/rehooks/local-storage

React hook which syncs localStorage[key] with the comp.
https://github.com/rehooks/local-storage

hooks localstorage react

Last synced: 3 months ago
JSON representation

React hook which syncs localStorage[key] with the comp.

Awesome Lists containing this project

README

        

# @rehooks/local-storage

[![All Contributors](https://img.shields.io/badge/all_contributors-8-orange.svg?style=flat-square)](#contributors-)

> React hook for enabling synchronization with local-storage.

[![npm version](https://badge.fury.io/js/%40rehooks%2Flocal-storage.svg)](https://www.npmjs.com/package/@rehooks/local-storage)
[![npm downloads](https://img.shields.io/npm/dw/@rehooks/local-storage)](https://www.npmjs.com/package/@rehooks/local-storage)

API Docs can be found [here](https://rehooks.github.io/local-storage).

## Table of Contents

- [@rehooks/local-storage](#rehookslocal-storage)
- [Table of Contents](#table-of-contents)
- [Features](#features)
- [Install](#install)
- [With Yarn](#with-yarn)
- [With NPM](#with-npm)
- [Usage](#usage)
- [Write to Storage](#write-to-storage)
- [Read From Storage](#read-from-storage)
- [Optionally use a default value](#optionally-use-a-default-value)
- [Delete From Storage](#delete-from-storage)
- [Using With Context](#using-with-context)
- [Full Example](#full-example)
- [Contributors ✨](#contributors-)

## Features

- Automatic JSON serialization
- Synchronization across multiple tabs
- Provides functions for updating the localStorage and triggering a state update outside of the component
- Type hinting via TypeScript

## Install

### With Yarn

```sh
yarn add @rehooks/local-storage
```

### With NPM

```sh
npm i @rehooks/local-storage --save
```

## Usage

### Write to Storage

This can be anywhere from within your application.

> Note: Objects that are passed to writeStorage are automatically stringified.
> This will not work for circular structures.

```jsx
import React from 'react';
import { writeStorage } from '@rehooks/local-storage';

let counter = 0;

const MyButton = () => (
writeStorage('i', ++counter)}>
Click Me

);

```

### Read From Storage

This component will receive updates to itself from local storage.

__Javascript__:

```jsx
import React from 'react';
import { useLocalStorage } from '@rehooks/local-storage';

function MyComponent() {
const [counterValue] = useLocalStorage('i'); // send the key to be tracked.
return (


{counterValue}



);
}
```

__Typescript__:

```tsx
import React from 'react';
import { useLocalStorage } from '@rehooks/local-storage';

function MyComponent() {
const [counterValue] = useLocalStorage('i'); // specify a type argument for your type
// Note: Since there was no default value provided, this is potentially null.
return (


{counterValue}



);
}
```

#### Optionally use a default value

> Note: Objects that are passed to useLocalStorage's default parameter will be automatically
> stringified. This will not work for circular structures.

```jsx
import React from 'react';
import { useLocalStorage } from '@rehooks/local-storage';

function MyComponent() {
// Note: The type of user can be inferred from the default value type
const [user] = useLocalStorage('user', { name: 'Anakin Skywalker' });
return (


{user.name}



);
}
```

### Delete From Storage

You may also delete items from the local storage as well.

```js
import { writeStorage, deleteFromStorage } from '@rehooks/local-storage';

writeStorage('name', 'Homer Simpson'); // Add an item first

deleteFromStorage('name'); // Deletes the item

const thisIsNull = localStorage.getItem('name'); // This is indeed null
```

### Using With Context

It is advisable to use this hook with context if you want to have a properly
synchronized default value. Using `useLocalStorage` in two different components
with the same key but different default values can lead to unexpected behaviour.

Using Context will also prevent components from rendering and setting
default values to the localStorage when you just want them to be deleted from localStorage
(assuming the context provider also does not re-render).

```jsx
import React, { createContext, useContext } from 'react';
import { useLocalStorage } from '@rehooks/local-storage';

const defaultProfile = { name: 'Spongekebob' };
const defaultContextValue = [defaultProfile, () => {}, () => {}];

const ProfileContext = createContext(defaultContextValue);

export const ProfileProvider = ({ children }) => {
const ctxValue = useLocalStorage('profile', defaultProfile);
return (

{children}

);
};

const useProfile = () => useContext(ProfileContext);

const App = () => {
const [profile] = useProfile();
return

{profile && profile.name}

;
};

export default () => {
return (



);
};
```

## Full Example

You may view this example [here on StackBlitz.](https://stackblitz.com/edit/react-vbrkjb?embed=1&file=index.js)

> Note: The writeStorage and deleteFromStorage functions are provided from useLocalStorage as well,
> and do not require you to specify the key when using them.

```jsx
import React, { Fragment } from 'react';
import { render } from 'react-dom';
import { writeStorage, deleteFromStorage, useLocalStorage } from '@rehooks/local-storage';

const startingNum = 0;

const Clicker = () => (

Clicker


{
writeStorage('num', localStorage.getItem('num')
? +(localStorage.getItem('num')) + 1
: startingNum
)
}}>
Increment From Outside

deleteFromStorage('num')}>
Delete From Outside


);

const IncrememterWithButtons = () => {
const [number, setNum, deleteNum] = useLocalStorage('num');

return (

{typeof(number) === 'number' ? number : 'Try incrementing the number!'}


setNum(number !== null ? +(number) + 1 : startingNum)}>Increment
Delete

);
};

const App = () => (

Demo





);

// Assuming there is a div in index.html with an ID of 'root'
render(, document.getElementById('root'));
```

## Contributors ✨

Thanks goes to these wonderful people ([emoji key](https://allcontributors.org/docs/en/emoji-key)):



Amit Solanki

πŸ’» πŸ“– πŸ€” πŸ‘€

Joe

πŸ’» πŸ’‘ πŸ€” 🚧 πŸ‘€ ⚠️

Fatih Kaya

πŸ’» ⚠️ πŸ›

Jarl AndrΓ© HΓΌbenthal

πŸ’» ⚠️ πŸ›

Jamie Kyle

πŸ’»

Albert Boehmler

πŸ’» πŸ›

Gabriel Dayley

πŸ’» πŸ›



Harley Alexander

🚧 πŸ’» πŸ› ⚠️

This project follows the [all-contributors](https://github.com/all-contributors/all-contributors) specification. Contributions of any kind welcome!