What is react-cookie?
The react-cookie package is a library for handling cookies in React applications. It provides hooks and components to easily set, get, and remove cookies, making it simple to manage user sessions and preferences.
What are react-cookie's main functionalities?
Setting a Cookie
This feature allows you to set a cookie using the `useCookies` hook. In this example, a cookie named 'user' is set with the value 'John Doe' when the login button is clicked.
import { useCookies } from 'react-cookie';
function App() {
const [cookies, setCookie] = useCookies(['user']);
const handleLogin = () => {
setCookie('user', 'John Doe', { path: '/' });
};
return (
<div>
<button onClick={handleLogin}>Login</button>
</div>
);
}
Getting a Cookie
This feature allows you to get a cookie using the `useCookies` hook. In this example, the value of the 'user' cookie is displayed in a paragraph.
import { useCookies } from 'react-cookie';
function App() {
const [cookies] = useCookies(['user']);
return (
<div>
<p>User: {cookies.user}</p>
</div>
);
}
Removing a Cookie
This feature allows you to remove a cookie using the `useCookies` hook. In this example, the 'user' cookie is removed when the logout button is clicked.
import { useCookies } from 'react-cookie';
function App() {
const [cookies, setCookie, removeCookie] = useCookies(['user']);
const handleLogout = () => {
removeCookie('user', { path: '/' });
};
return (
<div>
<button onClick={handleLogout}>Logout</button>
</div>
);
}
Other packages similar to react-cookie
js-cookie
js-cookie is a simple, lightweight JavaScript API for handling cookies. It is not specific to React but can be used in any JavaScript project. Compared to react-cookie, js-cookie requires more manual handling of cookies but offers more flexibility for non-React environments.
universal-cookie
universal-cookie is a library for handling cookies in both client and server environments. It provides a consistent API for managing cookies in JavaScript and is often used in conjunction with server-side rendering frameworks. Compared to react-cookie, universal-cookie is more versatile for isomorphic applications.
react-use-cookie
react-use-cookie is a React hook for managing cookies. It is similar to react-cookie but offers a simpler API with fewer features. It is suitable for projects that need basic cookie management without the additional functionality provided by react-cookie.
Universal cookies for React
Integrations
Getting started
npm install react-cookie
<CookiesProvider />
Set the user cookies
On the server, the cookies
props must be set using req.universalCookies
or new Cookie(cookieHeader)
withCookies(Component)
Give access to cookies by providing it using the cookies
prop.
Cookies
get(name, [options])
Get a cookie value
- name (string): cookie name
- options (object):
- doNotParse (boolean): do not convert the cookie into an object no matter what
getAll([options])
Get all cookies
- options (object):
- doNotParse (boolean): do not convert the cookie into an object no matter what
set(name, value, [options])
Set a cookie value
- name (string): cookie name
- value (string|object): save the value and stringify the object if needed
- options (object): Support all the cookie options from RFC 6265
- path (string): cookie path, use
/
as the path if you want your cookie to be accessible on all pages - expires (Date): absolute expiration date for the cookie
- maxAge (number): relative max age of the cookie from when the client receives it in second
- domain (string): domain for the cookie (sub.domain.com or .allsubdomains.com)
- secure (boolean): Is only accessible through HTTPS?
- httpOnly (boolean): Is only the server can access the cookie?
remove(name, [options])
Remove a cookie
- name (string): cookie name
- options (object): Support all the cookie options from RFC 6265
- path (string): cookie path, use
/
as the path if you want your cookie to be accessible on all pages - expires (Date): absolute expiration date for the cookie
- maxAge (number): relative max age of the cookie from when the client receives it in second
- domain (string): domain for the cookie (sub.domain.com or .allsubdomains.com)
- secure (boolean): Is only accessible through HTTPS?
- httpOnly (boolean): Is only the server can access the cookie?
Simple Example
import React from 'react';
import App from './App';
export default function Root() {
return (
<CookiesProvider>
<App />
</CookiesProvider>
);
}
import React, { Component } from 'react';
import { instanceOf } from 'prop-types';
import { CookiesProvider, withCookies, Cookies } from 'react-cookie';
import NameForm from './NameForm';
class App extends Component {
static propTypes = {
cookies: instanceOf(Cookies).isRequired
};
componentWillMount() {
const { cookies } = this.props;
this.state = {
name: cookies.get('name') || 'Ben'
};
}
handleNameChange(name) {
const { cookies } = this.props;
cookies.set('name', name, { path: '/' });
this.setState({ name });
}
render() {
const { name } = this.state;
return (
<div>
<NameForm name={name} onChange={this.handleNameChange.bind(this)} />
{this.state.name && <h1>Hello {this.state.name}!</h1>}
</div>
);
}
}
export default withCookies(App);
Server-Rendering Example
import React, { Component } from 'react';
import { instanceOf } from 'prop-types';
import { withCookies, Cookies } from 'react-cookie';
import NameForm from './NameForm';
class App extends Component {
static propTypes = {
cookies: instanceOf(Cookies).isRequired
};
componentWillMount() {
const { cookies } = this.props;
this.state = {
name: cookies.get('name') || 'Ben'
};
}
handleNameChange(name) {
const { cookies } = this.props;
cookies.set('name', name, { path: '/' });
this.setState({ name });
}
render() {
const { name } = this.state;
return (
<div>
<NameForm name={name} onChange={this.handleNameChange.bind(this)} />
{this.state.name && <h1>Hello {this.state.name}!</h1>}
</div>
);
}
}
export default withCookies(App);
import React from 'react';
import ReactDOMServer from 'react-dom/server';
import { CookiesProvider } from 'react-cookie';
import Html from './components/Html';
import App from './components/App';
export default function middleware(req, res) {
const markup = ReactDOMServer.renderToString(
<CookiesProvider cookies={req.universalCookies}>
<App />
</CookiesProvider>
);
const html = ReactDOMServer.renderToStaticMarkup(<Html markup={markup} />);
res.send('<!DOCTYPE html>' + html);
}
import React from 'react';
import ReactDOM from 'react-dom';
import { CookiesProvider } from 'react-cookie';
import App from './components/App';
const appEl = document.getElementById('main-app');
ReactDOM.render(
<CookiesProvider>
<App />
</CookiesProvider>,
appEl
);
require('babel-register');
const express = require('express');
const serverMiddleware = require('./src/server').default;
const cookiesMiddleware = require('universal-cookie-express');
const app = express();
app
.use('/assets', express.static('dist'))
.use(cookiesMiddleware())
.use(serverMiddleware);
app.listen(8080, function() {
console.log('Listening on 8080...');
});