@hitorisensei/react-use-cookie
TypeScript icon, indicating that this package has built-in type declarations

1.3.1 • Public • Published

useCookie

npm package

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>
  );
};

setUserToken accepts a second argument: options. Different to the named export, for this one it is the second not the third argument. Take a look at setCookie for more details.

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');
  // use to call your API etc
};

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:

{
  // The number of days the cookie is stored (defaults to 7)
  days: number;
  // The path of the cookie (defaults to '/')
  path: string;
}

Package Sidebar

Install

npm i @hitorisensei/react-use-cookie

Weekly Downloads

1

Version

1.3.1

License

MIT

Unpacked Size

22.3 kB

Total Files

16

Last publish

Collaborators

  • hitorisensei