A react hooks to use useState with localStorage persist
npm install @penseapp/uselocalstorage



This is a react hook that allows you to use the power of browser localstorage
and the useState react hook combined!
The API is the same, and you'll see no difference between them!
You can try this live version on: https://penseapp-uselocalstorage.web.app/
``tsx
import { useLocalStorage } from "@penseapp/uselocalstorage";
const [state, setState] = useLocalStorage
"keyName",
"useLocalStorage",
false // or a number
);
`
`sh`
yarn add @penseapp/uselocalstorage
or
`sh`
npm i @penseapp/uselocalstorage
Import the lib on your component
`tsx`
import { useLocalStorage } from "@penseapp/uselocalstorage";
Simple change the useState to useLocalStorage on any hooks and it's done.
Now you can reload your browser and your state will maintein
`diff
import React, { useState } from "react";
import { useLocalStorage } from "@penseapp/uselocalstorage";
const App: React.FC = () => {
- const [state, setstate] = useState
+ const [state, setstate] = useLocalStorage
return (
<>
Your React component...
>
);
};
export default App;
`
| Name | Type | Required | Default | Description |
| ------------ | --------------- | -------- | ------------------ | ----------------------------------------------- |
| key | string | true | | Key name from localStorage (Should be unique) |useState
| initialValue | any (Generic) | true | | Same as the hook |
| expire | number or false | false | 60 \* 30 (seconds) | Time in seconds to expiry (false to infinite) |
This lib use as dependecy the expired-storage, so you can controll your state by how much time it should persist on localStorage
You have two options:
- Set the time in seconds
- Set false to infinite
Examples
`tsx
// Never expires (infinite)
const [state, setstate] = useLocalStorage
// Expires in 1 minute
const [state, setstate] = useLocalStorage
// Expires in 1 hour
const [state, setstate] = useLocalStorage
// Expires in 12 hours
const [state, setstate] = useLocalStorage
``