The preferences, that is. User retention is an entirely different conversation. But as far as persisting a user's data goes, the approach is surprisingly straight forward.
When storing a user's data, it is important to keep security in mind. Don't save things like a user's password or a secret key where unwanted intrusions may occur. For the purposes of this demonstration, we will only be storing the user's theme preference.
In the we learned how to create a dark mode toggle button:
Lets take a closer look at our functionality. When we click the button, our styling toggles between light and dark mode, awesome! If you switch to dark mode and refresh, you may notice you're right back to light mode, as that is our default setting.
Lets fix this behavior by storing our preference using the
We'll need to update our
useEffect hook from it's current state:
to the following:
In this change, we've told our application to store a key value pair to our browser, but you may have noticed we are only setting the item and not using it to control our state. To accomplish this, we need to add another
useEffect hook above the one we just edited, it should look like this:
Lets take a closer look. We are using the
getItem method to retrieve the value of the key we set earlier, and using the
JSON.parse method to convert the string value to a .
We're leaving the dependency array empty, because we only want this to run on the initial mount of our application. With this change complete, we are now able to refresh our page, and our theme preference is loaded without us having to toggle the button.
In some cases, users will already have certain preferences available from their device, and we can use those to set our initial state. In this case, we can use the to check if the user has a theme preference set in their device.To accomplish this, we can edit the previous
useEffect hook to look like this:
We're using an
if statement to check if the user has a preference set in their device. If they do, we'll set the state to the value of the preference. If not, we'll use the
matchMedia api to check if the user prefers dark mode. If they do, we'll set the state to using the
prefers-color-scheme: dark media query. This will return a boolean value, and we'll set
prefersDarkMode to that value. This will trigger our initial
useEffect hook to run, and update our application to match the user's preference.
This is all it takes to persist data. This was just a small example, but many developers find this useful for storing a multitude of non-sensitive data, without having to make expensive calls to the server among many other creative uses.