React Custom Hook: useCookie
Tags: webdev, javascript, programming, react
Published: 2023-08-09 21:00:00

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

```javascript
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]
}
```

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.

```javascript
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>
        </>
    )
}
```

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.

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

> <u>Answer</u>: 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