Pull to refresh

React Custom Hook: useCookie

Level of difficulty Medium
Reading time 4 min
Views 1.6K

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)

    const deleteCookie = useCallback(() => {
    }, [name])

    return [value, updateCookie, deleteCookie]

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.

import useCookie from "./useCookie"

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

    return (
            <button onClick={() => update("Sally")}>Change Name To Sally</button>
            <button onClick={remove}>Delete Name</button>

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.

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.

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

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

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.

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

Rating 0
Comments 0
Comments Leave a comment