0.5.1 • Published 2 years ago
react-persist-local-storage v0.5.1
react-persist-local-storage
A React hook for persisting, syncing and managing state in local storage.
Supports object and string types.
Features
- Keeps React state in sync with local storage.
- Keeps local storage in sync between windows.
- Add, update and delete local storage items.
- Type hinting when using objects!
Example Usage:
Initial value as string:
import useLocalStorage from "react-persist-local-storage";
const Example = () => {
const key = "example.value";
const [value, setValue, deleteValue] = useLocalStorage(
key,
"string value"
);
return (
<div>
<input
value={value || ""}
onChange={(e) => setValue(e.target.value)}
/>
<p>{value}</p>
<button disabled={!value} onClick={() => deleteValue(key)}>
Delete "{key}"
</button>
</div>
);
};
export default Example;Initial value as object:
import useLocalStorage, {
LocalStorageValue
} from "react-persist-local-storage";
const Example = () => {
const key = "example.value";
const [value, setValue, deleteValue] = useLocalStorage(key, {
value: "example value"
});
return (
<div>
<input
value={JSON.stringify(value) || ""}
onChange={(e) =>
setValue(
JSON.parse(e.target.value) as LocalStorageValue<typeof value>
)
}
/>
{/*
'value' is typed!
'value' is nullable as it can be removed from local storage.
*/}
<p>{value?.value || ""}</p>
<button disabled={!value} onClick={() => deleteValue(key)}>
Delete "{key}"
</button>
</div>
);
};
export default Example;Reference
useLocalStorage(key, initialValue, options)
Parameters
key: The local storage key.initialValue: Initial value of the localstorage value.options.sync: Enable local storage syncing between windows.
Returns
[value, setValue, deleteItem]
- The serialized local storage value.
- Function for setting the local storage value.
- Function for removing the local storage item.
Development
Requirements
To install dependencies:
bun installBuild in watch mode:
Note: The build uses tsc instead of bun as Bun currenlty has a bug where React is bundled in the build which causes the Invalid hook call error. Once this has been fixed, bun will be used.
bun devRun example:
cd ./examples
bun dev0.5.1
2 years ago
0.5.0
2 years ago
0.4.2
2 years ago
0.4.1
2 years ago
0.4.0
2 years ago
0.3.0
2 years ago
0.2.2
2 years ago
0.2.1
2 years ago
0.2.0
2 years ago
0.1.1
2 years ago
0.1.0
2 years ago
0.0.24
2 years ago
0.0.23
2 years ago
0.0.22
2 years ago
0.0.21
2 years ago
0.0.20
2 years ago
0.0.19
2 years ago
0.0.18
2 years ago
0.0.17
2 years ago
0.0.16
2 years ago
0.0.15
2 years ago
0.0.14
2 years ago
0.0.13
2 years ago
0.0.12
2 years ago
0.0.11
2 years ago
0.0.10
2 years ago
0.0.9
2 years ago
0.0.8
2 years ago
0.0.7
2 years ago
0.0.6
2 years ago
0.0.5
2 years ago
0.0.4
2 years ago
0.0.3
2 years ago
0.0.2
2 years ago
0.0.1
2 years ago