When transitioning from classes to hooks, there are a few rules:
First, a few changes need to be done in the class component:
- remove as much code as possible from the constructor,
- use
componentDid<Cycle>instead of unsafecomponentWill<Cycle>:
| Instead of | Use these |
|---|---|
componentWillMount |
componentDidMount |
componentWillReceiveProps |
componentDidReceiveProps |
componentWillUpdate |
componentDidUpdate |
I recommend you to check react's doc if you want more informations on the deprecation of these methods.
Then those are the main hooks you will want to use:
- use one
useStatehook per field in the state, - use
useEffectinstead ofcomponentDidMount,componentDidReceiveProps,componentDidUpdateandcomponentWillUnmount, - use local variables instead of attributes / methods.
If those aren't enough, these are the final rules:
- if using local variables isn't possible, use
useCallbackfor methods anduseMemofor attributes, - use
useReffor refs or if you need to mutate a method/attribute in different places without triggering a re-render, - and if you need a
useEffectthat runs synchronously after each render (for specific ui interactions), useuseLayoutEffect.
If you want to see a concrete application of these rules, you can check this post in which I wrote a detailed migration of react-only
Top comments (0)