useLocalStorage hook в React JS

Использование localStorage и состояния useState в функциональном компоненте React JS.

useLocalSorage.js

import { useState, useEffect } from 'react';

function getStorageValue(key, defaultValue) {
	// getting stored value
	const saved = localStorage.getItem(key);
	const initial = JSON.parse(saved);
	return initial || defaultValue;
}

export const useLocalStorage = (key, defaultValue) => {
	const [value, setValue] = useState(() => {
		return getStorageValue(key, defaultValue);
	});

	useEffect(() => {
		// storing input name
		localStorage.setItem(key, JSON.stringify(value));
	}, [key, value]);

	return [value, setValue];
};

Использование:

import { useLocalStorage } from '../../utils/useLocalStorage';

const [value, setValue] = useLocalStorage(
 	'keyNameInLocalStorage', 
	'default value'
);