Skip to content

Instantly share code, notes, and snippets.

@lwkchan
Last active February 20, 2024 11:29
Show Gist options
  • Save lwkchan/2dfe69061ff4f4cc6606f48f36c07e6d to your computer and use it in GitHub Desktop.
Save lwkchan/2dfe69061ff4f4cc6606f48f36c07e6d to your computer and use it in GitHub Desktop.
Simple React hook to get/set Cookies with 'universal-cookie' package 🍪
import {useState} from 'react';
import Cookies from 'universal-cookie';
const useCookie = (key, options = {}) => {
const cookies = new Cookies();
const [item, setItemValue] = useState(() => {
if (cookies.get(key)) {
return cookies.get(key);
}
return null;
});
const setValue = (value, options) => {
setItemValue(value);
cookies.set(key, value, options);
};
const removeItem = (options) => {
cookies.remove(key);
};
return [item, setValue, removeItem];
};
export default useCookie;
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment