πͺ Custom React Hook to Get Cookie Value by Name πͺ
Do you ever find yourself needing to access cookie values in your React applications? I've got you covered with a simple and reusable custom React hook!
useCookie.ts
import { useEffect, useState } from 'react';
// Hook to get the public key from cookie
export function useCookie(cookieName: string): string | null {
const [cookieValue, setCookieValue] = useState<string | null>(null);
useEffect(() => {
const getCookie = (): string | null => {
const cookies = document.cookie.split(';').map(cookie => cookie.trim());
for (const cookie of cookies) {
const [name, value] = cookie.split('=');
if (name === cookieName) {
return decodeURIComponent(value);
}
}
return null;
};
setCookieValue(getCookie());
}, [cookieName]);
return cookieValue;
}
Sample usage
// Usage example:
const MyComponent = () => {
const userId = useCookie('user_id');
return (
<div>
User ID: {userId}
</div>
);
};
export default MyComponent;
Conclusion
With this hook, you can easily retrieve the value of a cookie by its name in your React components.
Let me know what you think! And feel free to share your thoughts or suggestions in the comments below. Happy coding! π