useCookie
A React hook for managing cookies with no dependencies.
Installation
npm install react-use-cookie
or
yarn add react-use-cookie
Usage
useCookie
import useCookie from 'react-use-cookie';
export default props => {
const [userToken, setUserToken] = useCookie('token', '0');
render(
<div>
<p>{userToken}</p>
<button onClick={() => setUserToken('123')}>Change token</button>
</div>
);
};
You can also specify an optional third argument - an options object with the following keys:
{
days: number;
path: string;
}
This package also has a few other exports that can be used directly.
getCookie
If you need to access a cookie outside of a React component, you can use the named getCookie
export:
import { getCookie } from 'react-use-cookie';
const getUser = () => {
const xsrfToken = getCookie('XSRF-TOKEN');
};
setCookie
If you need to set a cookie outside of a React component, you can use the named setCookie
export:
import { setCookie } from 'react-use-cookie';
const saveLocale = locale => {
setCookie('locale', locale);
};
You can also specify an optional third argument - the same options object as above:
{
days: number;
path: string;
}