/
aaronair
/
Test_task_rt_solution
Обзор
Документация
Войти
/
aaronair
/
Test_task_rt_solution
Код
Запросы
0
Задачи
Вики
Пакеты
0
Релизы
0
CI/CD
Аналитика
Безопасность
master
src/hooks/useLocalStorage.ts
38 строк
934 B
Ilikedrinkpivo
first_commit
28 май 2026, 14:51
28 май 2026, 14:51
b4498fc
Код
Авторство
О чём код?
import { useCallback, useEffect, useState } from "react"; function readValue<T>(key: string, initial: T): T { if (typeof window === "undefined") return initial; try { const raw = window.localStorage.getItem(key); if (raw === null) return initial; return JSON.parse(raw) as T; } catch { return initial; } } export function useLocalStorage<T>( key: string, initial: T, ): [T, (value: T | ((prev: T) => T)) => void] { const [value, setValue] = useState<T>(() => readValue(key, initial)); useEffect(() => { try { window.localStorage.setItem(key, JSON.stringify(value)); } catch { // ignore quota / serialization errors in prototype } }, [key, value]); const update = useCallback( (next: T | ((prev: T) => T)) => { setValue((prev) => typeof next === "function" ? (next as (p: T) => T)(prev) : next, ); }, [], ); return [value, update]; }