useWebStorage
useWebStorage stores your value in local or session storage in the browser.
Web Storage Type
{
"site": "tony.alves.dev"
}If you open another instance and use localStorage, you can watch the changes event for storage change. Alternatively you shouldn't be able to see changes on sessionStorage.
Code for example above
import { useState, useEffect } from "react";import { useWebStorage } from "@talves/use-web-storage";export const Example = (props) => {const [storage, setStorage, storageType, setStorageType] = useWebStorage("test-data",{ site: "tony.alves.dev" },{ type: "sessionStorage" });useEffect(() => {console.log("web-storage(js):", storage);}, [storage]);const handleChangeEvent = (e) => {setStorage({ site: e.target.value });};const onChangeType = (event) => {setStorageType(event.target.value);};return (<div><div><div><span>Web Storage Type</span><div onChange={onChangeType}><label><inputtype="radio"value="localStorage"name="storageType"defaultChecked={storageType === "localStorage"}/><span>localStorage</span></label><label><inputtype="radio"value="sessionStorage"name="storageType"defaultChecked={storageType === "sessionStorage"}/><span>sessionStorage</span></label></div></div><label><span>Site</span><inputplaceholder="Enter value"onChange={handleChangeEvent}value={storage.site}/></label>{storage && <pre>{JSON.stringify(storage, null, 2)}</pre>}</div></div>);};
Simple Color (localStorage)
"#FFE000"
Here's a simple example of how to use local storage and change the value. Refresh the page to see the value persist. Also open another browser window to see the value persist across pages and changing with an event listener.
Code for example above
export const ExampleColor = (props) => {const [bgColor, setBgColor] = useWebStorage("background-color", "#FFE000");useEffect(() => {console.log(bgColor);}, [bgColor]);const handleColorChange = (event) => {setBgColor(event.target.value);};return (<div><div><div><span>Simple Color (localStorage)</span></div><label><span>Color</span><inputplaceholder="Enter value"onChange={handleColorChange}value={bgColor}/></label><pre style={{ backgroundColor: bgColor }}>{JSON.stringify(bgColor, null, 2)}</pre></div></div>);};