Ever wish your app could remember things like a user’s theme choice, preferences, or other settings, even after a page reload? Good news: it absolutely can!
With Recoil, your trusty state management tool, and localStorage, the browser’s built-in memory, you can easily persist your app’s state. That means no more resetting the theme or losing data when users refresh or come back later.
And the best part? You don’t need anything complicated. just a few lines of code with Recoil and localStorage. It’s so easy, you’ll wonder why you didn’t do it sooner!
This small tweak makes your app seamless and user-friendly, like it has a memory that syncs with your users.
Ready to add persistence to your app with Recoil? Let’s get started!
First, check out my other blogs on Recoil to get a solid foundation. I cover basics like Recoil Intro Part and Recoil Hooks to help you get the most out of Recoil.
Main Advantages of Implementing State Persistence in Recoil with Local Storage –
Coding Example:
Let’s Implement the State Persistence in Recoil with Local Storage for Theme Preference
state.js –
import { atom } from 'recoil'; // Atom to store the mode (light or dark) export const modeState = atom({ key: 'modeState', // Unique ID for the atom default: 'light', });
App.js-
import React, { useEffect } from 'react'; import { useRecoilState } from 'recoil'; import { modeState } from './state'; const App = () => { const [mode, setMode] = useRecoilState(modeState); // Load mode from localStorage useEffect(() => { const savedMode = localStorage.getItem('modeState'); if (savedMode) { setMode(savedMode); // Set the mode if found in localStorage } }, [setMode]); // Save mode to localStorage whenever it changes useEffect(() => { localStorage.setItem('modeState', mode); document.body.className = mode; // Apply the mode to the body class }, [mode]); return ( <div> <h1>Current Mode: {mode}</h1> <button onClick={() => setMode(mode === 'light' ? 'dark' : 'light')}> Change Mode </button> </div> ); }; export default App;
Index.js –
import React from 'react'; import ReactDOM from 'react-dom'; import { RecoilRoot } from 'recoil'; import './index.css'; import App from './App'; ReactDOM.render( <RecoilRoot> <App /> </RecoilRoot>, document.getElementById('root') );
index.css-
/* Default light mode */ body.light { background-color: white; color: black; } /* Dark mode */ body.dark { background-color: #121212; color: white; } button { padding: 10px 20px; cursor: pointer; background-color: #007bff; color: white; border: none; border-radius: 5px; } button:hover { background-color: #0056b3; }
Explanation:
This app saves and loads the theme from localStorage, and the mode can be toggled between light and dark.
- State Management: The modeState atom in Recoil stores the current mode (light or dark).
- Persistence: On page load, the app checks localStorage for the saved mode. If found, it applies the saved mode. When the mode changes, it is saved back to localStorage.
- Mode Toggle: A button toggles between light and dark modes, updating the background color and saving the mode to localStorage.
- Page Refresh: The selected mode persists across page refreshes, maintaining the last chosen theme.
Output:
- When the app loads, it checks localStorage for a saved mode (light or dark) and uses it. If no mode is found, it defaults to light mode.
- Clicking the “Change Mode” button switches between light and dark modes and changes the background color.
- The app saves the selected mode to localStorage whenever it changes.
- When you refresh the page, the app gets the saved mode from localStorage and uses it, keeping the same mode.
In Inspect Mode (Developer Tools), go to the Application tab to see localStorage entries where the light/dark mode is saved. When the mode is toggled, the localStorage value updates with the new mode. After refreshing the page, the saved mode is retrieved from localStorage and applied, which you can verify by checking both localStorage and the body class in the Elements tab.
In short, using Recoil with localStorage saves user settings like the theme here between sessions and page reloads, making the experience more consistent and personalized.
Conclusion:
Using Recoil with localStorage is a win-win for both users and developers. For users, it means their preferences, like the theme, are saved across sessions, making the experience feel seamless and personalized every time they return. For developers, it takes the hassle out of managing state persistence. With Recoil handling the app’s state and localStorage automatically saving settings, developers can focus on building excellent features instead of worrying about saving and loading data. This combination makes the development process smoother, faster, and more efficient.
That’s a wrap for today! But don’t go too far. I’ll be diving into tools and techniques that make development easier and more exciting. Until then, keep experimenting, stay curious, and happy coding!
Source: Read MoreÂ