https://github.com/tylerwolff/useCookie
A React hook for managing cookies with no dependencies.
https://github.com/tylerwolff/useCookie
cookies hooks react
Last synced: about 1 year ago
JSON representation
A React hook for managing cookies with no dependencies.
- Host: GitHub
- URL: https://github.com/tylerwolff/useCookie
- Owner: tylerwolff
- Created: 2019-01-22T01:03:05.000Z (over 7 years ago)
- Default Branch: master
- Last Pushed: 2024-06-21T15:23:01.000Z (about 2 years ago)
- Last Synced: 2025-04-04T21:07:38.022Z (about 1 year ago)
- Topics: cookies, hooks, react
- Language: JavaScript
- Homepage:
- Size: 536 KB
- Stars: 151
- Watchers: 2
- Forks: 14
- Open Issues: 10
-
Metadata Files:
- Readme: README.md
- Changelog: CHANGELOG.md
Awesome Lists containing this project
README
# useCookie
[![npm package][npm-badge]][npm]
A React hook for managing cookies with no dependencies.
## Installation
```bash
npm install react-use-cookie
```
or
```bash
yarn add react-use-cookie
```
## Usage
### `useCookie`
```jsx
import useCookie from 'react-use-cookie';
export default (props) => {
const [userToken, setUserToken, removeUserToken] = useCookie('token', '0');
render(
{userToken}
setUserToken('123')}>Change token
Remove token
);
};
```
In this example you can also set custom cookie options by passing an options object to `setUserToken`:
```js
setUserToken('abcd', {
days: 365,
SameSite: 'Strict',
Secure: true,
});
```
See [setCookie](#setcookie) for more option information about this.
As a convenience this package also exports the get and set functions so they can be used directly.
### `getCookie`
If you need to access a cookie outside of a React component, you can use the
exported `getCookie` function:
```js
import { getCookie } from 'react-use-cookie';
const getUser = () => {
const xsrfToken = getCookie('XSRF-TOKEN');
// use to call your API etc
};
```
### `setCookie`
If you need to set a cookie outside of a React component, you can use the
exported `setCookie` function:
```js
import { setCookie } from 'react-use-cookie';
const saveLocale = (locale) => {
setCookie('locale', locale, {
days: 1,
domain: 'github.com',
SameSite: 'Lax',
Secure: true,
});
};
```
You can also specify cookie options as a third argument:
```tsx
{
// The number of days the cookie is stored (defaults to 7)
days?: number;
// The path of the cookie (defaults to '/')
path?: string;
// Browser defaults unless set
domain?: string;
SameSite?: 'None' | 'Lax' | 'Strict';
Secure?: boolean;
HttpOnly?: boolean;
}
```
### `removeCookie`
If you need to remove a cookie outside of a React component, you can use the
exported `removeCookie` function:
```js
import { removeCookie } from 'react-use-cookie';
removeCookie('token');
```
[npm-badge]: https://img.shields.io/npm/v/react-use-cookie.svg
[npm]: https://www.npmjs.org/package/react-use-cookie