According to this answer, the most reliable way still in 2019 to detect changes in cookies is to check document.cookie
on interval.
In React 16.8, we have useEffect
hook that we could use together with useState
hook to run a function on interval and cause the component to update when the value of document.cookie
has been updated, like
import React, { useState, useEffect } from 'react';
const MyComponent = props => {
const [latestCookie, setLatestCookie] = useState(document.cookie);
useEffect(() => {
const detectCookieUpdate = document.cookie !== latestCookie && setLatestCookie(document.cookie);
const interval = window.setInterval(detectCookieUpdate, 1000);
return () => window.clearInterval(interval);
});
return (
<Mfont>{quantity()}</Mfont>
);
};
This way we run a function every 1 second that checks if the value of document.cookie
is equal to the previous value. Since the value is always a string, it's safe to use strict comparison operator ===
and not do any checks on top of that. When the values don't match, we run setLatestCookie
provided by the state hook, causing the component to render again, and therefore making use of quantity
function that will run again.