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]
}
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>
</>
)
}
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)
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?
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.
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.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:
Using useCookie Custom Hook:
1) Abstraction and State Synchronization:
2) Code Cleanliness:
3) Ease of Use:
4) Customization and Context:
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.
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!