All Challengesadvanced
Custom React hook
Custom hooks are how AI encapsulates reusable logic. Understanding them is essential for reading modern React code.
reactcustom hookslocalStoragegenerics
typescript
function useLocalStorage<T>(key: string, initialValue: T) {
const [storedValue, setStoredValue] = React.useState<T>(() => {
try {
const item = window.localStorage.getItem(key)
return item ? JSON.parse(item) : initialValue
} catch {
return initialValue
}
})
function setValue(value: T) {
try {
setStoredValue(value)
window.localStorage.setItem(key, JSON.stringify(value))
} catch {
console.error('Could not save to localStorage')
}
}
return [storedValue, setValue] as const
}Question
What does the function passed to useState do, and why is it a function instead of a direct value?