Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Unexpected re-renders when the saved cookie is an object #536

Open
albertodeago opened this issue May 15, 2024 · 0 comments
Open

Unexpected re-renders when the saved cookie is an object #536

albertodeago opened this issue May 15, 2024 · 0 comments

Comments

@albertodeago
Copy link

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.

@albertodeago albertodeago changed the title Unexpected re-renders when the saved cookie as an object value Unexpected re-renders when the saved cookie is an object May 15, 2024
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

No branches or pull requests

1 participant