DEV Community

Ayc0
Ayc0

Posted on • Edited on • Originally published at ayc0.github.io

1

Migrating class components to hooks – rules

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 unsafe componentWill<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 useState hook per field in the state,
  • use useEffect instead of componentDidMount, componentDidReceiveProps, componentDidUpdate and componentWillUnmount,
  • 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 and useMemo 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), use useLayoutEffect.

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

Image of Datadog

Create and maintain end-to-end frontend tests

Learn best practices on creating frontend tests, testing on-premise apps, integrating tests into your CI/CD pipeline, and using Datadog’s testing tunnel.

Download The Guide

Top comments (0)

Heroku

This site is built on Heroku

Join the ranks of developers at Salesforce, Airbase, DEV, and more who deploy their mission critical applications on Heroku. Sign up today and launch your first app!

Get Started

👋 Kindness is contagious

Please leave a ❤️ or a friendly comment on this post if you found it helpful!

Okay