Skip to content

A React hook for managing cookies with no dependencies.

Notifications You must be signed in to change notification settings

neonaut/useCookie

 
 

Repository files navigation

useCookie

on npm

A React hook for managing cookies with no dependencies.

Installation

npm install @neonaut/use-cookie

or

yarn add @neonaut/use-cookie

Usage

useCookie

import useCookie from "@neonaut/use-cookie";

export default function MyComponent(props) {
  const [userToken, setUserToken] = useCookie("token");

  return (
    <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 "@neonaut/use-cookie";

function 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 "@neonaut/use-cookie";

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

About

A React hook for managing cookies with no dependencies.

Resources

Stars

Watchers

Forks

Packages

No packages published

Languages

  • TypeScript 88.4%
  • Nix 11.6%