Skip to content
This repository has been archived by the owner on Jun 17, 2024. It is now read-only.

How to keep updated react context value inside a callback in a custom hook #838

Closed
ilgianfra opened this issue Sep 9, 2020 · 2 comments
Closed

Comments

@ilgianfra
Copy link

Hi!

I have a userContext wrapped my app, I have a custom hook useAnalytics used to send analytics events and I got a Login component which performs the log in and changes the user value in the context and send the login event.

My problem is when I do a setUser inside my Login component the updating user data is not reflected in useAnalytics hook which sends always the user data in every event.

Here a sandbox: https://codesandbox.io/s/romantic-perlman-wzxti?file=/src/Login.js You can open the console and see the results after clicking SEND

Maybe this is an anti-pattern but it would be good to know why I get this behaviour.

Thanks!

@kentcdodds
Copy link
Owner

Hi @ilgianfra,

I answered your question in my Office Hours today. Here's a link to that: https://youtu.be/FdO2cphSH9Y?t=2533

Here's my finished codesandbox: https://codesandbox.io/s/jolly-einstein-28unz?file=/src/useAnalytics.js

Good luck!

@ilgianfra
Copy link
Author

ilgianfra commented Sep 15, 2020

Hi @kentcdodds,

First of all I am glad you noticed that I follow your blogpost :) yes that user provider is very familiar :)

Secondarily, maybe I should have put more info because I can't change the useAnalytics like that because it's been used in the whole application also when the user is not changing, that's why it was so hard to find a solution.
But I think, after watching the video, I have an idea maybe another hook, like a high order hook, which it handles the analytics when the user changes... 🤔

Btw, thanks a lot, and thanks for your work, it's very helpful for many devs!

See you on your blog!

Sign up for free to subscribe to this conversation on GitHub. Already have an account? Sign in.
Labels
None yet
Projects
None yet
Development

No branches or pull requests

2 participants