Unexpected re-renders when the saved cookie is an object
albertodeago opened this issue · 0 comments
Hello!
First of all thanks for the library, I'm using it since ages and it's an amazing one.
I think I've found a possible issue, let me try to explain it:
The shouldUpdate function is used to check wether the component will rerender with a new value, the problem is that if the cookie is an object (e.g. {"key": "value"}
) that shouldUpdate function will always return true
as the ===
will always resolve to false because the object references are going to be different between cookie reads.
This may seem not a problem, but, every time one cookie change (let's call it cookie-1
), all the listener of useCookies
occurrences will fire, so if I used three times useCookies
in my app, like:
// component 1
...
const [c, setC] = useCookies(["cookie-1"]);
// component 2
...
const [c, setC] = useCookies(["cookie-2"]);
// component 3
...
const [c, setC] = useCookies(["cookie-2"]);
All three 'listeners' will fire, and the shouldUpdate function will run three times (as expected).
The problem is that, if cookie-2
or cookie-3
are object values, that shouldUpdate
function will return true and cause a re-render of the component, even if we actually just changed cookie-1
This is a repo to easily reproduce it, the readme have all the steps to do it:
https://github.com/albertodeago/react-cookie-repro-obj
(I created the repro with next.js because it was faster, but it's not next.js related)
I'm happy to open a PR to fix this, if you agree with me this is an improvement.