react-cookie is a utility library for React applications that provides a universal (isomorphic) solution for managing browser cookies, enabling consistent cookie handling across both client-side and server-side rendering (SSR) environments. Its current stable version is 8.1.0, with frequent updates addressing dependencies and minor improvements, typically on a monthly cadence for patch releases and less frequently for minor/major versions as features or breaking changes are introduced. Key differentiators include its integration with the underlying `universal-cookie` library for core logic, offering React-specific hooks (`useCookies`) and a provider pattern (`CookiesProvider`) for easy consumption within React component trees. It simplifies reading, setting, and removing cookies by abstracting away the browser's `document.cookie` API and Node.js server request headers, making it particularly useful for applications requiring robust cookie management in an SSR context.
npm install react-cookieVerified import paths — ran on the pinned version, not inferred.
This quickstart demonstrates setting up `CookiesProvider` and using the `useCookies` hook to interact with a cookie named 'my-cookie-name'.
Ensure your project uses React.js version 16.3.0 or higher. For older React versions (15.x), use `react-cookie` versions 0.0-2.2.
Understand that `httpOnly` cookies are exclusively for server-side access to enhance security. Do not attempt to manipulate them from the browser. For client-accessible data, avoid the `httpOnly` flag.
On the server, pass the cookie instance obtained from the incoming request (e.g., `req.universalCookies` if using `universal-cookie-express`, or `new Cookies(req.headers.cookie)`) to the `CookiesProvider` prop, like `<CookiesProvider cookies={serverCookiesInstance}>`.Always specify the exact cookie names your component depends on in the `dependencies` array to optimize performance and prevent excessive re-renders, e.g., `useCookies(['my-specific-cookie'])`.
Wrap your component tree, or at least the components using `useCookies`, with `CookiesProvider` at a higher level in your application.
Ensure you are using `import { useCookies } from 'react-cookie';` and `react-cookie` is listed in your `package.json` and `node_modules`.The `setCookie` method automatically stringifies objects, so ensure you're providing the expected type or explicitly cast if TypeScript complains without real reason. If the `value` is an object, `react-cookie` handles serialization.