How to Remove all Cookies in React.js?

When dealing with persisting data in a React application, we sometimes want to completely remove all cookie information from the browser. This helps to clear any data that might interfere with some functionality in the UI.

So, how can you remove all cookies in React.js? Cookies can be removed in React.js by using the following methods:

Let explore both these options.

Using react-cookie

The react-cookie package provides a robust system of dealing with cookie management. We can leverage its .remove() method to get rid of  current cookies in the browser:

cookies.remove("user");

To ensure that cookies are cleared once the browser shuts down, we can put the following  event listener in componentDidMount:

componentDidMount() {
  window.addEventListener("beforeunload", (e) => {
    e.preventDefault();
    cookies.remove("user");
  });
}

The beforeunload event is fired when the window, the document, and its resources are about to be unloaded. 

Additionally, this can also be accomplished using new React hooks!

const [cookies, setCookie, removeCookie] = useCookies(["user"]);
removeCookies();

Using native DOM methods

Using document.cookie we can iterate through all current cookies and erase them like so:

document.cookie.split(";").forEach((c) => {
  document.cookie = c
    .replace(/^ +/, "")
    .replace(/=.*/, "=;expires=" + new Date().toUTCString() + ";path=/");
});

So whats going on here?

  • We split the cookies by ; to create an array.
  • We iterate through the array of cookies to replace its content with an expiry date of today (new Date().toUTCString())
  • Having today’s time and date essentially voids the cookie and it is removed from the browser.

Gareth Dunne

Senior JavaScript Engineer and creator of JSdiaries. Passionate about the latest in web technologies and how it can provide value for my clients.