I have been learning React hooks lately and I am currently facing useState
. I know this is a way to use state in functional components but I wonder what the real benefits are above using a React.PureComponent
with this.state
?
Is it really bad practice now to use a PureComponent
instead of useState
or useEffect
? Does this make the app "faster"?
I know this question sounds dumb because useState
is the new kid on the block but I just need a valid reason to refactor my old components into this new pattern?
Edit: I've been using hooks for a while now and like them a lot (changed my opinion), however it increases the learning curve and there are pitfalls:
Good stuff:
this
(easily avoided with arrow functions in classes tbh)Bad stuff:
memo
, useCallback
, useMemo
, useRef
, useEffect
, useLayoutEffect
, useState
etc. Ask a beginner how to debounce a callback - suddenly it's a hard problem.this
for much more problems such as:useRef
etc)useRef
(and I believe useCallback
) are quietly created and discarded every render in favour of the first one created.Side note: Solid framework has a better implementation of hooks which don't require dependencies
TL&DR: There is no need to refactor all old components.
useState
and others react hooks introduce a new way to implement your components. They can be helpful as they simplify code reusability. You can move your specific logic to a custom hook and use it in several components. Custom hooks can call useState
and they don't have any possibility to damage state from other useState
calls. It allows you to split component logic more wisely.
So there are 2 main profits of using useState
: code reusability and code splitting.
When it's better to refactor old components? Let's say, you have 3-4 legacy components, which make similar things, but it's complicated to reuse code. You can rewrite such components to hooks, move all common logic to custom hook and reuse this hook in all of these components.
Also, if you have any additional questions you can take a look to this https://reactjs.org/docs/hooks-intro.html article
And one important thing: PureComponent equivalent in "functional component world" is to wrap your function with React.memo
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With