{"id":14275,"url":"\/distributions\/14275\/click?bit=1&hash=bccbaeb320d3784aa2d1badbee38ca8d11406e8938daaca7e74be177682eb28b","title":"\u041d\u0430 \u0447\u0451\u043c \u0437\u0430\u0440\u0430\u0431\u0430\u0442\u044b\u0432\u0430\u044e\u0442 \u043f\u0440\u043e\u0444\u0435\u0441\u0441\u0438\u043e\u043d\u0430\u043b\u044c\u043d\u044b\u0435 \u043f\u0440\u043e\u0434\u0430\u0432\u0446\u044b \u0430\u0432\u0442\u043e?","buttonText":"\u0423\u0437\u043d\u0430\u0442\u044c","imageUuid":"f72066c6-8459-501b-aea6-770cd3ac60a6"}

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.

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.

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

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 Cookies.remove("username")

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.

0
Комментарии
-3 комментариев
Раскрывать всегда