How to Manage and Access Cookies in React: A Complete Guide to React Cookies

Use the react-cookie library to read, write, and delete browser cookies via the useCookies hook, which returns a tuple of [cookies, setCookie, removeCookie] for idiomatic React state management.

Managing user preferences and session data in React applications requires persistent client-side storage. While the native document.cookie API is cumbersome and error-prone, react cookies handling becomes straightforward with the react-cookie library, which provides a hooks-based interface that integrates naturally with React's component lifecycle and supports server-side rendering.

The react-cookie library offers several advantages over manual cookie management:

  • Declarative API: The useCookies hook returns a [cookies, setCookie, removeCookie] tuple that can be used directly in any function component.
  • SSR-friendly: The hook accepts an initialCookies object when rendering on the server, preventing hydration mismatches.
  • Automatic JSON handling: Values are automatically serialized and deserialized, simplifying storage of complex user-preference objects.
  • Cookie options: You can set path, expires, maxAge, secure, sameSite, and other standard attributes via a single options object.
  • Built-in TypeScript support: Types are exported for autocompletion and compile-time safety.

Core Architecture and Source Files

Understanding the internal structure of react-cookie helps you debug issues and extend functionality. The library is organized into focused modules:

The useCookies Hook

Located in src/useCookies.js, this is the primary interface for components. It reads cookies from document.cookie (or from the initial object you provide) and returns the current cookie map together with mutator functions.

CookiesProvider Context

The CookiesProvider component, defined in src/CookiesProvider.js, wraps the part of your component tree that needs cookie access. It injects the cookie context so that any descendant component can call useCookies without directly touching the DOM.

Server-Side Rendering Support

When rendering on the server, you instantiate a CookiesProvider with the request's cookie header. This keeps the initial cookie state consistent between server and client, preventing hydration errors.

Implementing React Cookies in Your Application

Installation and Basic Setup

First, add the library to your project:

npm install react-cookie

Then wrap your application with the provider in your entry file:

// src/index.tsx
import React from 'react';
import ReactDOM from 'react-dom/client';
import { CookiesProvider } from 'react-cookie';
import App from './App';

ReactDOM.createRoot(document.getElementById('root')!).render(
  <React.StrictMode>
    <CookiesProvider>
      <App />
    </CookiesProvider>
  </React.StrictMode>
);

Reading and Writing User Preferences

The useCookies hook provides a tuple containing the current cookie state and mutator functions. Here is a complete example for persisting a theme preference:

// src/components/ThemeToggle.tsx
import React from 'react';
import { useCookies } from 'react-cookie';

const ThemeToggle: React.FC = () => {
  const [cookies, setCookie, removeCookie] = useCookies(['theme']);
  const [theme, setTheme] = React.useState<string>(cookies.theme ?? 'light');

  const toggleTheme = () => {
    const newTheme = theme === 'light' ? 'dark' : 'light';
    setTheme(newTheme);
    setCookie('theme', newTheme, { 
      path: '/', 
      maxAge: 60 * 60 * 24 * 365 // 1 year
    });
  };

  const clearPreference = () => {
    setTheme('light');
    removeCookie('theme', { path: '/' });
  };

  return (
    <div>
      <p>Current theme: <strong>{theme}</strong></p>
      <button onClick={toggleTheme}>Toggle Theme</button>
      <button onClick={clearPreference}>Reset</button>
    </div>
  );
};

export default ThemeToggle;

Handling Authentication Tokens Securely

For session data and authentication tokens, configure security options to mitigate XSS and CSRF attacks:

// Setting a secure auth token
setCookie('auth_token', token, {
  path: '/',
  secure: true,            // HTTPS only
  sameSite: 'strict',      // CSRF protection
  maxAge: 60 * 60 * 24,    // 1 day
  // Note: httpOnly cannot be set client-side; 
  // it must be set by the server via Set-Cookie header
});

Server-Side Rendering with Next.js

To prevent hydration mismatches in Next.js, parse the request cookies on the server and pass them to CookiesProvider:

// pages/_app.tsx
import type { AppProps } from 'next/app';
import { CookiesProvider } from 'react-cookie';
import { parse } from 'cookie';

function MyApp({ Component, pageProps }: AppProps) {
  const initialCookies = pageProps.__cookies ?? {};

  return (
    <CookiesProvider cookies={initialCookies}>
      <Component {...pageProps} />
    </CookiesProvider>
  );
}

export default MyApp;
// pages/index.tsx
import { GetServerSideProps } from 'next';
import { parse } from 'cookie';
import ThemeToggle from '../components/ThemeToggle';

export const getServerSideProps: GetServerSideProps = async ({ req }) => {
  const cookieHeader = req.headers.cookie ?? '';
  const cookies = parse(cookieHeader);

  return { props: { __cookies: cookies } };
};

export default function Home() {
  return (
    <main>
      <h1>Welcome</h1>
      <ThemeToggle />
    </main>
  );
}

The react-cookie library is modularized into specific responsibilities. Understanding these files helps when debugging or contributing:

File Purpose
src/index.js Re-exports the public API (useCookies, CookiesProvider).
src/CookiesProvider.js Implements the React context that stores the cookie map and mutation functions.
src/useCookies.js Core hook that reads document.cookie, parses it, and returns the [cookies, setCookie, removeCookie] tuple.
src/parseCookies.js Utility that converts the raw cookie string into a JavaScript object.
src/setCookie.js Helper that builds the Set-Cookie string with all optional attributes.
src/removeCookie.js Helper that deletes a cookie by setting an expired date.

Summary

  • react-cookie provides a declarative, hooks-based API for managing browser cookies in React applications.
  • The useCookies hook returns a tuple of [cookies, setCookie, removeCookie] for reading and mutating cookie state.
  • Wrap your application with CookiesProvider to inject the cookie context throughout your component tree.
  • For server-side rendering, pass the parsed request cookies to CookiesProvider to prevent hydration mismatches.
  • Always specify the path option when removing cookies to ensure proper deletion.
  • Security-sensitive cookies should use secure: true and sameSite: 'strict' to mitigate XSS and CSRF attacks.

Frequently Asked Questions

To remove a cookie, call the removeCookie function returned by the useCookies hook and pass the cookie name along with the same path option used when setting the cookie. For example: removeCookie('theme', { path: '/' }). If the path does not match the original setting, the browser will retain the cookie.

Yes, react-cookie is designed to work with SSR frameworks like Next.js. You must parse the Cookie header from the incoming request on the server and pass the resulting object to the CookiesProvider via its cookies prop. This ensures the server-rendered HTML matches the client's initial cookie state, preventing hydration errors.

You can store authentication tokens using react-cookie, but you must configure security options properly. Always set secure: true to ensure HTTPS transmission, use sameSite: 'strict' to prevent CSRF attacks, and specify an appropriate maxAge or expires value. Note that the httpOnly flag cannot be set from client-side JavaScript and must be configured by your backend server when issuing the cookie.

react-cookie automatically serializes JavaScript objects to JSON strings when setting cookies and deserializes them back to objects when reading. This means you can pass complex user preference objects directly to setCookie without manual JSON.stringify calls, and retrieve them as parsed objects from the cookies map returned by useCookies.

Have a question about this repo?

These articles cover the highlights, but your codebase questions are specific. Give your agent direct access to the source. Share this with your agent to get started:

Share the following with your agent to get started:
curl -s "https://instagit.com/install.md"

Works with
Claude Codex Cursor VS Code OpenClaw Any MCP Client

Maintain an open-source project? Get it listed too →