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:
- By using
cookies.remove()
in the react-cookie library - By accessing
document.cookie
in the DOM.
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.
If you are looking to get your dream software engineering position I’d recommend subscribing to Mosh’s all-access membership to improve your skills as a React developer.