Using localStorage in Remix
I wanted to get some more experience working with GraphQL mutations, so I worked on a new feature for my site that enabled a user to “like” a blog article. I ran into a little gotcha that is kind of obvious now that I know the solution but wasn’t obvious at the time.
I didn’t think I needed to be fancy and store the “like” in the database and associate with the user, so I decided that tracking whether the user had liked the article in localStorage was enough and then keep track of the total article like count in the database. Seems easy enough right?
The Problem
This was my first approach in retrieving whether or not the user had liked the article from localStorage:
And this is the error that I was getting:
The Fix
At first I was 🤔, but the fix is super simple and totally makes sense. Remix renders on the server, but I wanted to run this in the browser, so I simply needed to wrap it in a useEffect:
This is actually captured in the Remix docs, but it was kind of buried.