| | | | | 🍪 Custom React Hook to Get Cookie Value by Name 🍪 | | |  | | Photo by Jonny Gios / Unsplash | | 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.tsimport { 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;
ConclusionWith 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! 😊 | | | | | |
❤️ Support This Blog
If this post helped you, you can support my writing with a small donation.
Thank you for reading.
Comments
Post a Comment