Friday , February 26 2021

Persisting React State in localStorage · react, Hacker News

Let’s say we’re building a calendar app, like Google Calendar. The app lets you toggle between three different displays: month, week, and day.

Toggling between views in a typical calendar application

Personally, I always want to see the “Week” view. It gives me everything I need to know about the current day, while also giving me a peek at what’s coming up in the next couple of days.

Thankfully, calendar apps know that users have strong preferences around this kind of thing, and the toggle is “sticky” . If I switch from “week” to “month” and refresh the page, the “month” view is the new default; it sticks.

Conversely, it’s super annoying when form controls aren’t sticky. For example: every month, I create 4-5 expenses through Expensify. Every single time, I have to swap the default currency from USD to CAD. Why can’t it remember that I’m Canadian ??

In this tutorial we’ll see how we can create a custom React hook to abstract away the “stickiness”, so we get it for free whenever we need it.

Here’s what our custom hook looks like:


function ) useStickyState ( defaultValue , key ) {

const [value, setValue] React

(useState) ( ( ) => { const stickyValue

= (window) (localStorage) getItem ( key ) return [name, value]. stickyV alue

== null

(JSON) parse ( stickyValue ) : defaultValue [name, value]. ;

) useEffect ( ( =>



(localStorage ) (setItem) ( key ), (JSON) stringify ( value ) ; , [key, value] ) return [value, setValue] } To show how it works, here’s a quick counter demo with a sticky count. Try clicking it a few times, and then refresh this page:

If this code is not clear to you, fear not! The rest of this tutorial explains it in greater detail 💫

This hook makes a single assumption, which is reasonably safe in React apps: the value powering a form input is held in React state.

Here’s a non-sticky implementation of a form control to switch between values:




(CalendarView) = ) => { const = (React ) . useState ( ‘day’ ; return > select (onChange) = { ev == setMode (() () target (value ) } option value = day (Day) option > ) (option (value)= (week ) > option > option value = month ”() (Month option >

select >

{ }




We can use our new “sticky” variant by swapping out the hook:



  const     CalendarView 

= ( => ({)

const = useStickyState (day) 'calendar-view' ;


About admin

Check Also

Server-Side Only React with Next, Hacker News

You know that feeling you get sometimes that the web is broken?You visit a seemingly simple website with little or no interactivity, yet somehow it sends you 2 MB of JavaScript to digest. You're half way down the article that you're reading and suddenly: client-side rendering kicks in, resets everything. You try to find your…

Leave a Reply

Your email address will not be published. Required fields are marked *