Skip to content

useLocalStorageState

useLocalStorageState: Custom useState hook implementation using LocalStorage, with immutable getter state function and to remove key from localStorage.

Demo

INFO

The component has:

  • An internal useLocalStorage state with key demo and initialState prova from which gets remove function.
  • A Child component 1 that uses useLocalStorage with read mode and key demo to read from localStorage.
  • A Child component 2 that uses useLocalStorage with write mode and key demo to write to LocalStorage with an onSubmit form event with a input text value.
  • An useEffect that invokes remove function and delete item with key demo from localStorage when the component unmounts.

When component is mounted, the Child1 state is prova. It can be changed by Child2. If you change state and open the page into another tab, after mounting, the Child1 display the new value of state and every changes made is reflected in both tabs.

Loading demo…
Show source code
tsx
import { BaseSyntheticEvent, memo, useCallback } from "react";
import { useEffectOnce, useLocalStorageState } from "../../../..";

const Child = memo(() => {
	const [state] = useLocalStorageState<string>({key:"demo", opts: {mode: "read"}});
	return (<>
		<h3>Child component 1</h3>
		<p>State is {state}</p>
	</>)
})

const Child2 = memo(() => {
	const [setState] = useLocalStorageState<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 UseLocalStorageState = () => {
	const [, , , remove] = useLocalStorageState({ key: "demo", initialState: "prova" });
	const clear = useCallback(() => remove(), [remove]);

	useEffectOnce(() => {
		return () => clear();
	})

	return (<>
		<Child />
		<br />
		<Child2/>
	</>);
}

UseLocalStorageState.displayName = "UseLocalStorageState";

export { UseLocalStorageState };

Released under the MIT License.