useSessionStorageState
useSessionStorageState: Custom useState hook implementation using sessionStorage, with immutable getter state function and to remove key from sessionStorage.
Demo
INFO
The component has:
- An internal useSessionStorage state with key demo and initialState prova from which gets remove function.
- A Child component 1 that uses useSessionStorage with read mode and key demo to read from sessionStorage.
- A Child component 2 that uses useSessionStorage with write mode and key demo to write to sessionStorage with an onSubmit form event with a input text value.
- An useEffect that invokes remove function and delete item with key demo from sessionStorage when the component unmounts.
When component is mounted, the Child1 state is prova. It can be changed by Child2. If you open the page into another tab, changes aren't reflected in both tabs.
Loading demo…
Show source code
tsx
import { BaseSyntheticEvent, useCallback, useEffect } from "react";
import { useSessionStorageState } from "../../../..";
const Child = () => {
const [state] = useSessionStorageState<string>({key:"demo", opts: {mode: "read"}});
return (<>
<h3>Child component 1</h3>
<p>State is {state}</p>
</>)
}
const Child2 = () => {
const [setState] = useSessionStorageState<string>({key:"demo", opts: {mode: "write"}});
return (<>
<h3>Child component 2</h3>
<form onSubmit={(e: BaseSyntheticEvent) => {
setState(e.target[0].value);
e.preventDefault();
}}>
<input type="text" />
</form>
</>)
}
const UseSessionStorageState = () => {
const [, , , remove] = useSessionStorageState({ key: "demo", initialState: "prova" });
const clear = useCallback(() => remove(), [remove]);
useEffect(() => {
return () => {
clear();
}
}, [clear]);
return (<>
<Child />
<br />
<Child2/>
</>);
}
UseSessionStorageState.displayName = "UseSessionStorageState";
export { UseSessionStorageState };