Building Custom Hooks: The Rules, the Pattern, and What Not to Abstract

Hands-on practice for this lecture. Work through the exercises and quizzes to reinforce what you've learned.

1

Exercise 1 of 1

Build useLocalStorage

Live editor: implement a useLocalStorage custom hook that wraps useState and syncs to localStorage — so preferences survive page refreshes.

Task

Implement useLocalStorage(key, initialValue) — a custom hook that works like useState but persists its value to localStorage.

  • Initialize from localStorage.getItem(key) (fall back to initialValue if absent)
  • Return [value, setValue] — same API as useState
  • Call localStorage.setItem in a useEffect whenever the value changes
  • Use JSON.parse / JSON.stringify to support any serializable value
Loading editor…
Practice: Building Custom Hooks: The Rules, the Pattern, and What Not to Abstract — Interactive Exercises | Durgesh Rai