Hone logo
Hone
Problems

React Custom Hook: useCookie for Simplified Cookie Management

Managing cookies directly in React components can become repetitive and cumbersome. This challenge asks you to create a reusable useCookie hook that simplifies setting, getting, and deleting cookies, providing a cleaner and more maintainable way to interact with cookies within your React applications. This hook will abstract away the complexities of the document.cookie string manipulation.

Problem Description

You need to implement a custom React hook called useCookie that provides a simple interface for managing cookies. The hook should accept a cookie name as an argument and return an object with functions for:

  • read(): Retrieves the value of the cookie by its name. Returns null if the cookie doesn't exist.
  • write(value: string, options?: CookieOptions): Sets or updates the cookie's value. The options parameter is optional and allows specifying attributes like path, domain, maxAge (in seconds), and secure.
  • delete(): Deletes the cookie by its name.

Key Requirements:

  • The hook must be written in TypeScript.
  • The CookieOptions type should be defined as an interface with the following properties:
    • path?: string;
    • domain?: string;
    • maxAge?: number;
    • secure?: boolean;
    • sameSite?: 'Strict' | 'Lax' | 'None';
  • The write function should correctly encode the cookie value and construct the document.cookie string, including any provided options.
  • The delete function should set the cookie's maxAge to -1 to effectively delete it.
  • The hook should handle edge cases gracefully, such as invalid cookie names or options.
  • The hook should not cause unnecessary re-renders when cookie values haven't changed.

Expected Behavior:

  • Calling useCookie('myCookie') should return an object with read, write, and delete functions.
  • read() should return the cookie's value if it exists, otherwise null.
  • write() should set the cookie with the specified value and options.
  • delete() should remove the cookie.
  • Changes to cookie values should trigger re-renders in components that use the hook.

Edge Cases to Consider:

  • Cookie names containing special characters.
  • Cookie values containing special characters.
  • Invalid maxAge values (e.g., negative numbers).
  • Missing or invalid path or domain options.
  • Cookie names that are empty strings or null/undefined.

Examples

Example 1:

Input: Cookie name: 'session_id', write value: '12345', options: { maxAge: 3600 }
Output: Cookie 'session_id' is set with value '12345' and maxAge of 3600 seconds.
Explanation: The `write` function should correctly set the cookie with the provided value and maxAge.

Example 2:

Input: Cookie name: 'user_name', read()
Output: 'JohnDoe' (assuming a cookie 'user_name' with value 'JohnDoe' exists)
Output: null (if the cookie 'user_name' does not exist)
Explanation: The `read` function should return the cookie's value if it exists, otherwise null.

Example 3:

Input: Cookie name: 'cart_items', delete()
Output: Cookie 'cart_items' is deleted.
Explanation: The `delete` function should set the cookie's maxAge to -1, effectively removing it.

Constraints

  • The hook must be compatible with modern browsers that support cookies.
  • The maxAge option must be a non-negative integer.
  • The path and domain options, if provided, must be valid strings.
  • The secure option must be a boolean.
  • The sameSite option must be one of 'Strict', 'Lax', or 'None'.
  • The hook should avoid unnecessary re-renders.

Notes

  • Consider using useEffect to manage the cookie's lifecycle.
  • You'll need to parse the document.cookie string to retrieve cookie values. Be mindful of the format: name=value; path=path; domain=domain; max-age=maxAge; secure; sameSite=sameSite.
  • Encoding and decoding cookie values might be necessary to handle special characters. encodeURIComponent and decodeURIComponent can be helpful.
  • Think about how to handle errors or invalid input gracefully.
  • Focus on creating a clean, reusable, and well-documented hook.
Loading editor...
typescript