DEV Community

Cover image for React Custom Hook: useCookie
Sergey Leschev
Sergey Leschev

Posted on • Updated on

React Custom Hook: useCookie

In this article series, we embark on a journey through the realm of custom React hooks, discovering their immense potential for elevating your development projects. Our focus today is on the "useCookie" hook, one of the many carefully crafted hooks available in the collection of React custom hooks.

Github: https://github.com/sergeyleschev/react-custom-hooks

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]
}
Enter fullscreen mode Exit fullscreen mode

The useCookie hook allows you to effortlessly handle cookies by providing a concise interface. Upon initialization, useCookie retrieves the cookie value with the specified name. If the cookie exists, it returns its value; otherwise, it sets the cookie to the default value provided. This ensures a seamless experience for your users, as the desired data is readily available.

One of the key advantages of this custom hook is the ability to update the cookie value. The updateCookie function, returned by useCookie, enables you to modify the value of the cookie. By invoking this function with a new value and optional options, such as expiration or path, you can instantly update the cookie. Additionally, the hook conveniently updates the state, keeping your application in sync with the modified cookie.

In scenarios where you need to remove a cookie, the deleteCookie function comes to the rescue. Simply call this function, and it will remove the specified cookie from the browser. The hook takes care of updating the state, ensuring that your application reflects the removal of the cookie.

import useCookie from "./useCookie"

export default function CookieComponent() {
    const [value, update, remove] = useCookie("name", "John")

    return (
        <>
            <div>{value}</div>
            <button onClick={() => update("Sally")}>Change Name To Sally</button>
            <button onClick={remove}>Delete Name</button>
        </>
    )
}
Enter fullscreen mode Exit fullscreen mode

The useCookie custom hook is highly versatile and can be utilized in various contexts. It is particularly beneficial when working with user preferences, authentication tokens, or any data that needs to persist across different sessions. Whether you are building a simple login form, a shopping cart, or a feature-rich application, useCookie simplifies cookie management, saving you valuable development time.

Question: I think that work with cookie would be better on server side, not on the client. Because security.

Answer: You bring up an important consideration regarding security when working with cookies. While it's true that handling sensitive information should be primarily done on the server side, there are situations where client-side cookie management, like the useCookie custom hook described in the article, can be appropriate and beneficial.
Client-side cookies are often used for non-sensitive data like user preferences, session tokens, and UI-related states. These cookies can enhance user experience by persisting data across sessions and improving the overall usability of a web application. However, when dealing with sensitive data, such as authentication tokens or private user information, it's indeed recommended to handle those aspects on the server side due to security concerns.
The decision to use client-side or server-side cookie management depends on the specific requirements of your application and the nature of the data you're dealing with. Both approaches have their merits.

Full Version | React Custom Hooks:
https://dev.to/sergeyleschev/supercharge-your-react-projects-with-custom-hooks-pl4

Top comments (5)

Collapse
 
noblica profile image
Dušan Perković • Edited

Same question here as I had on the first post - why would you do this?

You're already using the js-cookie library for accessing cookies, and the cookie state is maintained inside...well the browser cookie.

Why would you additionally need to wrap this in a react state? What benefit does this add?

Collapse
 
sergeyleschev profile image
Sergey Leschev

This custom hook enhances cookie management in React. While js-cookie directly interacts with browser cookies, the useCookie hook abstracts this process, offering benefits such as streamlined cookie handling and synchronization with React state. This abstraction simplifies updates, removals, and state management, aiding in scenarios like user preferences and authentication tokens. It's a tool to make cookie-related tasks more efficient within a React application.

Collapse
 
noblica profile image
Dušan Perković

I get that, but I'm trying to think of a real life use-case.

Generally cookies are used for authentication, so if you need to replace a cookie, you probably need to refresh the entire page. At that point, there's no need for a state update, because a full page refresh is going to re-render everything anyway. Maybe you're using cookies for something else?

Also I don't really see how this is streamlined. It's just wrapping the js-cookie calls. I would see that if setting a cookie took multiple lines of code, but these just aren't. So I'm just trying to understand what the use-case is here.

Thread Thread
 
sergeyleschev profile image
Sergey Leschev • Edited

The useCookie custom hook enhances cookie management in React by simplifying updates, removals, and state management. While js-cookie interacts with browser cookies directly, useCookie abstracts the process, aiding scenarios like user preferences and authentication tokens. It's particularly useful when cookies need to persist across sessions or for efficient handling in complex applications.

Using js-cookie Directly:

import Cookies from "js-cookie"

// Set a cookie
Cookies.set("username", "john_doe")

// Get a cookie
const username = Cookies.get("username")

// Delete a cookie
Cookies.remove("username")
Enter fullscreen mode Exit fullscreen mode

Using useCookie Custom Hook:

// Inside a component
const [username, setUsername] = useCookie("username", "john_doe")

// setUsername("new_username") can be used to update the cookie

// The hook abstracts away the direct interaction with js-cookie
Enter fullscreen mode Exit fullscreen mode

1) Abstraction and State Synchronization:

  • Direct js-cookie: You need to manage cookie state separately from React state, which could lead to inconsistency.
  • useCookie Custom Hook: Abstracts away the interaction with js-cookie and synchronizes the cookie value with React state. This simplifies state management and ensures consistency between cookies and React components.

2) Code Cleanliness:

  • Direct js-cookie: You need to manage cookie-related logic directly within your components, which could clutter your code.
  • useCookie Custom Hook: Encapsulates the cookie logic within a reusable hook, making your component code cleaner and more focused on its main functionality.

3) Ease of Use:

  • Direct js-cookie: You have to remember the js-cookie API methods and manually handle cookie updates and deletions.
  • useCookie Custom Hook: Provides a simplified interface. You only need to call the hook once, and it returns the cookie value, update function, and delete function.

4) Customization and Context:

  • Direct js-cookie: If you want to apply custom logic or use cookies within a larger context, you have to implement it yourself.
  • useCookie Custom Hook: Offers a consistent pattern for cookie management across components, making it easier to implement custom logic or integrate with context providers.

Using the useCookie custom hook enhances the cookie management process by abstracting away the low-level details of js-cookie usage, providing a clean and synchronized approach to handling cookies within a React application.

Thread Thread
 
noblica profile image
Dušan Perković

Thank you for the detailed explanation 🙂

I still disagree and think this is overkill in most cases, and that you should just use the js-cookie library directly, instead of adding another layer of abstraction. But I appreciate you engaging in this discussuion with me!