See comment below thanks :)
Last active
June 2, 2024 11:33
-
-
Save mithi/5c3a24ba62f7c309ccb3ef8988729ece to your computer and use it in GitHub Desktop.
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Hi!
First of all, thank you for taking the time to speak with me during the refactoring session. I learned a lot and really enjoyed the conversation!
I just wanted to share something I learned recently that is quite interesting related to our discussion regarding the
useLocalStorage
hook. You asked me if there is a way to accomplish the same functionality without usinguseEffect
and on the fly I couldn't think of any.
Then you proposed the following solution:
I said that that could work and I don't see anything wrong with it. Interestingly enough, today I was reading a section of the
react.gg
course, and it was almost the same example he brought up in the discussion that this wasn't enough, and we really need to use anuseEffect
when synchronizing with some outside system such as alocalStorage
.Attached are some of the most relevant screenshots of the article including his code.
He brings up two things. One is that it violates two of three simple rules, which "Rule 0: When a component renders, it should do so without running into any side effect" and "Rule 2: If a side effect is synchronizing your component with some external system,
put that side effect inside useEffect".
The discussion for the reasoning behind each rule is quite long, but for rule 0, one of the most important reasons, is that
and he brings up exactly the lazy initialization of use state and argues:
And talks a little bit about server-side rendering. (See screenshots). I know the app we have is a purely client side app so we don't really care about server-side rendering that much.
But then again, in my personal opinion it wouldn't hurt to just follow the simple rules that is prescribed, by just simply adding around just 3 lines of code. No need to violate any rules, the way we try to never violate the
exhaustive deps
rule of hooks even though we believe it should be okay not to include functions inside the array of dependencies.Anyway, just wanted to share this, and hope you check out the screenshots. Thanks :)
Screenshot of the initial implementation which he thinks is not good enough
Screenshot of where he says lazy initialization in
useState
by accessinglocalStorage
is not a good ideaScreenshot of the solution which he prescribes with the use of
useEffect