
Why Use a Custom Hook for Cookies?
While JavaScript's document.cookie provides access to cookies, it returns all cookies as a single string. Parsing this string repeatedly across your codebase can lead to duplicated logic and errors. A custom hook like getCookie simplifies cookie retrieval, ensuring consistent behavior.
The getCookie Implementation
Here's the implementation of the getCookie function:
javascriptCopy code
const getCookie = (name) => {
const cookies = document.cookie
.split(";")
.map((cookie) => cookie.trim())
.filter((cookie) => cookie.startsWith(`${name}=`));
if (cookies.length === 0) {
return null;
}
return decodeURIComponent(cookies[0].split("=")[1]);
};
export default getCookie;Example Usage
Imagine you have a cookie named authToken and want to retrieve its value:
import getCookie from "./getCookie";
const token = getCookie("authToken");
if (token) {
console.log("Auth Token:", token);
} else {
console.log("Auth Token not found");
}