Skip to content

mate-academy/react_use-local-storage

Repository files navigation

Persist State with useLocalStorageState

Read the task guideline before you start.

❗️❗️❗️ BEFORE OPENING A PULL REQUEST, PROOF‑READ YOUR CODE WITH THE CHECKLIST. ❗️❗️❗️

s Custom‑hook challenge, but this time the focus is persistence.


Task description

Create and export a useLocalStorageState React hook that turns any piece of component state into durable state backed by localStorage.

API

const [state, setState, reset] = useLocalStorageState(
  key,          // string – localStorage key
  defaultValue, // any  – fallback when key missing or invalid
  options       // optional { serialize, deserialize }
);
  • serialize(value) – converts any value to a string (defaults to JSON.stringify).
  • deserialize(raw) – converts the stored string back to a value (defaults to JSON.parse).
  • reset() – clears the key and puts state back to defaultValue.

Simplified brief: No cross‑tab synchronisation, no expiry logic, no extras. Just persist and reset.

Rules of operation

  1. Initial value On the first render, check window.localStorage:

    • If the key exists, read and deserialize it.
    • If not, fall back to defaultValue.
  2. Persistence Whenever state changes, serialize it and write to localStorage under the same key.

  3. Reset helper The reset function should:

    • Remove the key from localStorage.
    • Set React state back to defaultValue.

About

No description, website, or topics provided.

Resources

License

Stars

Watchers

Forks

Releases

No releases published

Packages

 
 
 

Contributors