Migrating class components to hooks – rules
2 min read • Posted on August 18, 2020
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 information on the deprecation of these methods.
Then those are the main hooks you will want to use:
- use one
useState
hook per field in the state, - use
useEffect
instead ofcomponentDidMount
,componentDidReceiveProps
,componentDidUpdate
andcomponentWillUnmount
, - 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
useCallback
for methods anduseMemo
for attributes, - use
useRef
for refs or if you need to mutate a method/attribute in different places without triggering a re-render, - and if you need a
useEffect
that 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:
Migrating class components to hooks This article is an applied example of how I migrated the library `react-only` from classes to hooks