One data grid for JavaScript, React, Vue & Angular. Sorting, filtering, virtualization, pinning, and CSV export included. Early access $199 $349 → [Get it now]

How to persist state with cookies in React

Persisting state with cookies is ideal when you need server-side access to client data or cross-domain sharing capabilities that localStorage cannot provide. As the creator of CoreUI with extensive React experience since 2014, I’ve used cookie-based persistence for authentication tokens, user preferences, and SSR-compatible state management. The most practical approach combines React hooks with the js-cookie library for reliable cookie manipulation. This method ensures data persistence while providing server-side accessibility for universal applications.

Use the js-cookie library with React hooks to persist state in cookies with server-side compatibility.

import { useState, useEffect } from 'react'
import Cookies from 'js-cookie'

function App() {
    const [theme, setTheme] = useState(() => {
        return Cookies.get('theme') || 'light'
    })

    useEffect(() => {
        Cookies.set('theme', theme, { expires: 30 })
    }, [theme])

    return (
        <button onClick={() => setTheme(theme === 'light' ? 'dark' : 'light')}>
            Current theme: {theme}
        </button>
    )
}

This code initializes state from an existing cookie value using lazy initial state, defaulting to ’light’ if no cookie exists. The useEffect hook automatically saves the theme to a cookie whenever it changes, with a 30-day expiration. Unlike localStorage, cookies are accessible on the server during SSR and can be shared across subdomains when configured properly.

Best Practice Note:

This is the approach we use in CoreUI dashboard templates for theme persistence across server and client. Always set appropriate expiration dates and consider cookie size limitations (4KB max) for optimal performance.


Speed up your responsive apps and websites with fully-featured, ready-to-use open-source admin panel templates—free to use and built for efficiency.


About the Author

Subscribe to our newsletter
Get early information about new products, product updates and blog posts.
How to validate an email address in JavaScript
How to validate an email address in JavaScript

What is the difference between typeof and instanceof in JavaScript
What is the difference between typeof and instanceof in JavaScript

How to conditionally add attributes to React components
How to conditionally add attributes to React components

How to force a React component to re-render
How to force a React component to re-render

Answers by CoreUI Core Team