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