Close Menu
    DevStackTipsDevStackTips
    • Home
    • News & Updates
      1. Tech & Work
      2. View All

      Sunshine And March Vibes (2025 Wallpapers Edition)

      May 16, 2025

      The Case For Minimal WordPress Setups: A Contrarian View On Theme Frameworks

      May 16, 2025

      How To Fix Largest Contentful Paint Issues With Subpart Analysis

      May 16, 2025

      How To Prevent WordPress SQL Injection Attacks

      May 16, 2025

      Microsoft has closed its “Experience Center” store in Sydney, Australia — as it ramps up a continued digital growth campaign

      May 16, 2025

      Bing Search APIs to be “decommissioned completely” as Microsoft urges developers to use its Azure agentic AI alternative

      May 16, 2025

      Microsoft might kill the Surface Laptop Studio as production is quietly halted

      May 16, 2025

      Minecraft licensing robbed us of this controversial NFL schedule release video

      May 16, 2025
    • Development
      1. Algorithms & Data Structures
      2. Artificial Intelligence
      3. Back-End Development
      4. Databases
      5. Front-End Development
      6. Libraries & Frameworks
      7. Machine Learning
      8. Security
      9. Software Engineering
      10. Tools & IDEs
      11. Web Design
      12. Web Development
      13. Web Security
      14. Programming Languages
        • PHP
        • JavaScript
      Featured

      The power of generators

      May 16, 2025
      Recent

      The power of generators

      May 16, 2025

      Simplify Factory Associations with Laravel’s UseFactory Attribute

      May 16, 2025

      This Week in Laravel: React Native, PhpStorm Junie, and more

      May 16, 2025
    • Operating Systems
      1. Windows
      2. Linux
      3. macOS
      Featured

      Microsoft has closed its “Experience Center” store in Sydney, Australia — as it ramps up a continued digital growth campaign

      May 16, 2025
      Recent

      Microsoft has closed its “Experience Center” store in Sydney, Australia — as it ramps up a continued digital growth campaign

      May 16, 2025

      Bing Search APIs to be “decommissioned completely” as Microsoft urges developers to use its Azure agentic AI alternative

      May 16, 2025

      Microsoft might kill the Surface Laptop Studio as production is quietly halted

      May 16, 2025
    • Learning Resources
      • Books
      • Cheatsheets
      • Tutorials & Guides
    Home»Development»State Persistence in Recoil using Local Storage

    State Persistence in Recoil using Local Storage

    December 26, 2024

    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 –

    Key benefits of persistence in recoil

    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.

    1. State Management: The modeState atom in Recoil stores the current mode (light or dark).
    2. 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.
    3. Mode Toggle: A button toggles between light and dark modes, updating the background color and saving the mode to localStorage.
    4. Page Refresh: The selected mode persists across page refreshes, maintaining the last chosen theme.

     

    Output:

     

    Output

    1. 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.
    2. Clicking the “Change Mode” button switches between light and dark modes and changes the background color.
    3. The app saves the selected mode to localStorage whenever it changes.
    4. 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.

    Inspect mode persistence

    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 

    Facebook Twitter Reddit Email Copy Link
    Previous ArticleDynamic Component Rendering in Vue.js: When and How to Use It
    Next Article How to Use Vue.js Transitions for Smooth UI Animations

    Related Posts

    Security

    Nmap 7.96 Launches with Lightning-Fast DNS and 612 Scripts

    May 17, 2025
    Common Vulnerabilities and Exposures (CVEs)

    CVE-2024-47893 – VMware GPU Firmware Memory Disclosure

    May 17, 2025
    Leave A Reply Cancel Reply

    Continue Reading

    What is torrenting? BitTorrent, legal issues, how it works, and more

    Development

    These Google Pixel buds have replaced over-ear headphones for me when traveling – here’s why

    Development

    I changed 10 settings on my Pixel phone to instantly improve the user experience

    News & Updates

    Intel offers a two-year extended warranty for crashing chips. Here’s what you need to know

    Development

    Highlights

    FIM – universal image viewer

    February 17, 2025

    FIM (Fbi IMproved) is a highly customizable and scriptable image viewer. It aims to be…

    Skype Will Shut Down on May 5, As Microsoft Shifts to Teams

    February 28, 2025

    Pirated Copies of Microsoft Office Used to Distribute Frequent Malware in South Korea

    May 31, 2024

    Monitor not paper-y enough? A 25-inch color E Ink monitor just dropped for *checks notes* $1,900

    May 1, 2025
    © DevStackTips 2025. All rights reserved.
    • Contact
    • Privacy Policy

    Type above and press Enter to search. Press Esc to cancel.