React Hooks Migration

Contents

  • Component Comparisons throughout versions
  • Advantages
  • React Hooks in General
  • Hook Migration
  • Redux Hooks
  • React Router Hooks

React Component before ES6

PS:  create-react-class is a separate package after v16

React Component with ES6

React Component with Hooks

Stable Release: v16.8 - Feb 2019

Advantages of using React Hooks

  • solves binding/context problems
  • no this!
  • reusable logic of lifecycle methods
  • less boilerplate code
  • straight forward code reading
  • less complex DOM tree (no HOCs)

Context/Binding Problems

  • bind at constructor
  • bind at where it called
  • arrow function

bind at constructor

bind at where it called

bind with arrow function

with hook

sharing repeated lifecycle logic

not applicable with class components

sharing repeated lifecycle logic

applicable with hooks

React Hooks

  • useState*
  • useEffect*
  • useRef*
  • useReducer
  • useCallback
  • useMemo
  • useContext
  • useImperativeHandle
  • useLayoutEffect
  • useDebugValue

React Hooks

React Hooks

Migration

  • State Migration
  • Lifecycle migration
  • Ref migration
  • Reuse as custom hook if repeated throughout the app

State Migration

Do you update multiple items with single action?

 

No -> useState

Yes -> (maybe) useReducer

Lifecycle Migration

useEffect for all:

  • componentDidMount
  • componentDidUpdate
  • componentWillUnmount

Lifecycle Migration

  • useEffect called after every render, if no dependency
  • called only after  mounted and cleaned before unmounting when  dependencies is empty array
  • Conditionally called w.r.t dependencies (like didUpdate)

Third Party Libraries

  • React Router (Sep 2019)
  • React-Redux (Jun 2019)
  • Fancy Form Library (!?)
  • or others...

Before Hooks

Now

React Router

Before Hooks

Now

React Redux

CODING TIME!

Comparison

(in small demo application)

Line of code: 347

Line of code: 334

*No types: Typescript, Flow or prop-types

Thank you for listening

Any questions?

React Hooks Migration

By Özgün Bal

React Hooks Migration

  • 104