DEV Community

Discussion on: 3 amazing REACT HOOKS to keep your code organized neatly

Collapse
 
eecolor profile image
EECOLOR

Please note that these comments are written with a good intention, to help you not to bring you down.

Performing Asynchronous Actions

I really encourage you to watch this video about react-query: youtube.com/watch?v=seU46c6Jz7E

It 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:

const ... = useAsync(someAsyncFunction, { immediate: true })
Enter fullscreen mode Exit fullscreen mode

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:

const mountedRef = React.useRef(false)

useEffect(
  () => {
    mountedRef.current = true
    return () => { mountedRef.current = false }
  },
  []
)
Enter fullscreen mode Exit fullscreen mode

Updating LocalStorage or SessionStorage

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.

Collapse
 
dglsparsons profile image
Douglas Parsons

Hey, thanks for the feedback. Some super-useful looking resources there, and some gotchas I definitely hadn't thought about.

<3