https://github.com/alexmarqs/react-use-local-storage
📦 React hook npm package to persist and sync state with localStorage
https://github.com/alexmarqs/react-use-local-storage
hacktoberfest local-storage localstorage react react-hooks ssr synchronization typescript
Last synced: 3 months ago
JSON representation
📦 React hook npm package to persist and sync state with localStorage
- Host: GitHub
- URL: https://github.com/alexmarqs/react-use-local-storage
- Owner: alexmarqs
- License: mit
- Created: 2021-07-26T18:09:27.000Z (almost 4 years ago)
- Default Branch: main
- Last Pushed: 2022-04-03T09:12:24.000Z (about 3 years ago)
- Last Synced: 2025-01-03T09:45:43.173Z (5 months ago)
- Topics: hacktoberfest, local-storage, localstorage, react, react-hooks, ssr, synchronization, typescript
- Language: TypeScript
- Homepage:
- Size: 399 KB
- Stars: 3
- Watchers: 1
- Forks: 0
- Open Issues: 0
-
Metadata Files:
- Readme: README.md
- License: LICENSE
Awesome Lists containing this project
README
# @alexmarqs/react-use-local-storage
[](https://badge.fury.io/js/%40alexmarqs%2Freact-use-local-storage)
[](https://bundlephobia.com/package/@alexmarqs/react-use-local-storage)
[](https://codecov.io/gh/alexmarqs/react-use-local-storage)
[](https://github.com/alexmarqs/react-use-local-storage/actions)
[](https://opensource.org/licenses/MIT)> React hook to persist and sync state with localStorage. Typescript + SSR supported.
## 🔨 Install
With NPM
```shell
npm install @alexmarqs/react-use-local-storage
```With Yarn
```shell
yarn add @alexmarqs/react-use-local-storage
```## 🚀 Features
- Typescript support
- SSR support
- 100% test coverage
- Syncronization support to track changes across browser tabs (Window storage event subscription) - available via additional option (check API or Usage section)
- Non string values support (`JSON.parse()` and `JSON.stringify()` are used to decode/encode information from/to localStorage)
- Bad usage detection (for example, an error will be generated if multiple hook instances are detected)
- [Functional updates](https://reactjs.org/docs/hooks-reference.html#functional-updates) are supported (similar to React `useState`)
- No dependencies!## 📄 API
### useLocalStorage(key, defaultValue, options?)
| Argument | Type | Required? | Description |
| ------------ | ------------------------------------------------------------------------------- | -------------------------------------------------------- | ------------------------------------------------------ |
| key | `string` | Yes | The local storage key |
| defaultValue | `any` (with typescript you can explicity pass the type as `useLocalStorage`) | Yes | The initial value of the data |
| options | `{ sync: boolean }` | No. The default value for the **sync** option is `false` | **sync**: enables synchronization between broswer tabs |## 🎮 Usage
> If you are not using Typescript please ignore the types.
```tsx
import useLocalStorage from '@alexmarqs/react-use-local-storage';
// Named export alternative: import { useLocalStorage } from '@alexmarqs/react-use-local-storage';// Scenario 1
const [todos, setTodos] = useLocalStorage('todos', ['Todo 1', 'Todo 2']);// Scenario 2
type UserConsent = {
analytics: boolean;
marketing: boolean;
};
const [userConsent, setUserConsent] = useLocalStorage('user-consent', {
analytics: false,
marketing: false,
});// Scenario 3 (enable sync between browser tabs)
const [todos, setTodos] = useLocalStorage('todos', [], { sync: true });
```### Example 1
```tsx
import React from 'react';
import ReactDOM from 'react-dom';
import useLocalStorage from '@alexmarqs/react-use-local-storage';const App = () => {
const [value, setValue] = useLocalStorage('your-key', 'your-initial-value');return (
Set value to store in Local Storage
Value:{' '}
setValue(e.target.value)}
/>
);
};ReactDOM.render(, document.getElementById('root'));
```### Example 2 (using with React Context API)
```tsx
import React, { createContext, useContext } from 'react';
import ReactDOM from 'react-dom';
import useLocalStorage from '@alexmarqs/react-use-local-storage';// This code can be extracted to a TodosContext file
type Todos = string[];
type TodosContextData = [Todos, React.Dispatch>];const TodosContext = createContext([[], () => {}] as TodosContextData);
export const TodosProvider = ({ children }) => {
const ctxTodos = useLocalStorage('todos', [], { sync: true });
return {children};
};export const useTodos = () => {
const context = useContext(TodosContext);
if (context === undefined) {
throw new Error('useTodos can only be used inside TodosProvider');
}
return context;
};// App entry point (index)
const App = () => {
const [todos, setTodos] = useTodos();return (
Todos
{todos.length === 0
? 'No todos in the local storage'
: `You have ${todos.length} todos in the local storage`}
{/**
* Do something more, example: Add new todos
*/}
);
};ReactDOM.render(
,
document.getElementById('root')
);
```## License
MIT License © [alexmarqs](https://github.com/alexmarqs)