Published on
-
1 mins read

useCookie Hook - a simple way to work with cookies

Authors
  • avatar
    Name
    Seraj Vahdati
    Twitter
    @seraj

useCookie implementation

useCookie.js
import { useState, useCallback } from "react"
import Cookies from "js-cookie"
export default function useCookie(name, defaultValue) {
const [value, setValue] = useState(() => {
const cookie = Cookies.get(name)
if (cookie) return cookie
Cookies.set(name, defaultValue)
return defaultValue
})
const updateCookie = useCallback(
(newValue, options) => {
Cookies.set(name, newValue, options)
setValue(newValue)
},
[name]
)
const deleteCookie = useCallback(() => {
Cookies.remove(name)
setValue(null)
}, [name])
return [value, updateCookie, deleteCookie]
}

usage:

DisplayName.js
import useCookie from "./useCookie"
function DisplayName() {
const [value, update, remove] = useCookie("name", "Doe")
return (
<>
<div>{value}</div>
<button onClick={() => update("Seraj")}>Change Name To Seraj</button>
<button onClick={remove}>Delete Cookie</button>
</>
)
}
export default DisplayName;