-
Notifications
You must be signed in to change notification settings - Fork 52
Commit
This commit does not belong to any branch on this repository, and may belong to a fork outside of the repository.
Merge pull request #2884 from ever-co/feat/create-generic-useLocalSto…
…rageState-hook [Feat]: Add Generic useLocalStorageState hook for localStorage management
- Loading branch information
Showing
2 changed files
with
32 additions
and
8 deletions.
There are no files selected for viewing
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,30 @@ | ||
"use client" | ||
import { useState, useEffect } from 'react'; | ||
/** | ||
* Custom hook to manage state that is synchronized with `localStorage`. | ||
* | ||
* @template T - The type of the state value. | ||
* @param {string} key - The key under which the value is stored in `localStorage`. | ||
* @param {T} defaultValue - The default value to use if the key is not found in `localStorage`. | ||
* | ||
* @returns {[T, React.Dispatch<React.SetStateAction<T>>]} - Returns a stateful value and a function to update it. | ||
* | ||
* @example | ||
* const [calendar, setCalendar] = useLocalStorageState<ChangeCalendar>('calendar-timesheet', 'Calendar'); | ||
* | ||
* - The state `calendar` will be initialized with the value from `localStorage` if it exists, or 'Calendar' if not. | ||
* - Any updates to `calendar` will be reflected in `localStorage`. | ||
*/ | ||
|
||
export const useLocalStorageState = <T,>(key: string, defaultValue: T) => { | ||
const [state, setState] = useState<T>(() => | ||
(typeof window !== 'undefined' && window.localStorage.getItem(key) as T) || defaultValue | ||
); | ||
useEffect(() => { | ||
if (typeof window !== 'undefined') { | ||
window.localStorage.setItem(key, state as any); | ||
} | ||
}, [state, key]); | ||
|
||
return [state, setState] as const; | ||
}; |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters