13
12902

How to set cookie, read cookie and delete cookie in React

Reading Time: 2 minutes

Saving information into cookie or local storage is still an important function when developing website. Hence, we will be going though on how to set cookie, read and delete cookie in React using plugins. Javascript version can refer to here.

Usage of cookies:

Cookies are a very common type of storage mechanism for any webpage to store information that needs to exist even if user restart their browser or after it crash. Hence, these information is considered to be stateful.

Here are some of the common properties of a cookie (Maybe different based on browsers):

  • Maximum size of 4KB or 4096 Bytes per cookie
  • Maximum of 20 cookies per domain

For example is the storage of user information so that the user does not need to re-login even after they restart the application.

Installation

To perform cookie operations easily in react, we will be using a plugin known as react-cookie via npm.

// Install plugin into your application
npm i react-cookie

Set Cookie

To start setting a cookie, first we will need to import CookieProvider and wrap it around the main App component.

To set a cookie, we will also need to import useCookies. The apply useCookies to a state while assignment it a cookie name that will be stored into the browser.

// ... Some other imports
import { CookiesProvider } from 'react-cookie';
import { useCookies } from 'react-cookie';

const App = () => {
  const [cookie, setCookie] = useCookies(['valueName']);

  const handleChange = (data) => {
    setCookie('valueName', data, { path: '/' });
  }
};

class App extends Component {
   render() {
     return (<input type="text" value={cookie.valueName} onChange={handleChange}>);
   }
 }

ReactDOM.render(
  <CookiesProvider>
    <App />
  </CookiesProvider>, 
  document.getElementById('root')
);

Read Cookie

Since we have already assign a state to the cookie, we can read the cookie from the state’s object value.

let cookieValue = cookie.valueName;

Delete Cookie

In order to delete a cookie, what we have to do is to update the cookie to have an expire date from the old dates. But in react-cookie, we only have to declare a new function in the declarator and execute to remove;

Let’s look at the below example.

const [cookie, setCookie, removeCookie] = useCookies(['valueName']);

// Remove cookie
removeCookie('valueName');

Conclusion

With react-cookie plugin, react developers are having easier time to work with the cookies in a react-like environment instead of going back to the default javascript method.

Show Comments

No Responses Yet

Leave a Reply