Your version of mounted could cause some confusion in the future. It is initialized to true, but at that point the component is not yet mounted. I would suggest this:
Your implementation can cause problems when used in a server-side rendering scenario. It will always log an error because window.localStorage will be undefined.
Another tricky problem can occur when two different components use it with the same key. They will get out-of-sync.
The above things might not be problematic in your situation, but I think its good to be aware of.
Authenticating users
One of the most common problems with using context is that people do not provide a stable value. In your version this is also the case. The useAuthProvider creates an object which is passed directly to the value property of the provider.
The result is that for every render of ProvideAuth all users of the context will re-render, even if nothing actually changed. The solution for this would be to use React.memo to create the resulting object.
I hope you value this feedback. If you need help fixing these problems or finding solution let me know.
Please note that these comments are written with a good intention, to help you not to bring you down.
I really encourage you to watch this video about
react-query
: youtube.com/watch?v=seU46c6Jz7EIt convinced me that we should switch from our own custom hook to
react-query
for these types of things.Some feedback on your own implementation:
When you define an interface for your hooks, it helps to name boolean arguments:
Your version of
mounted
could cause some confusion in the future. It is initialized totrue
, but at that point the component is not yet mounted. I would suggest this:Your implementation can cause problems when used in a server-side rendering scenario. It will always log an error because
window.localStorage
will be undefined.Another tricky problem can occur when two different components use it with the same key. They will get out-of-sync.
The above things might not be problematic in your situation, but I think its good to be aware of.
One of the most common problems with using context is that people do not provide a stable
value
. In your version this is also the case. TheuseAuthProvider
creates an object which is passed directly to thevalue
property of the provider.The result is that for every render of
ProvideAuth
all users of the context will re-render, even if nothing actually changed. The solution for this would be to useReact.memo
to create the resulting object.I hope you value this feedback. If you need help fixing these problems or finding solution let me know.
Hey, thanks for the feedback. Some super-useful looking resources there, and some gotchas I definitely hadn't thought about.
<3