Search code examples
reactjsoptimizationcoding-stylereact-hooks

Which is the best `useReducer` -> reducer function declaration


Looking at the react doc, there is an initial way to do it. But like many others, it's rarely the efficient way.

So, I wonder which is the best / efficient / cleaner way to declare the reducer function since it's a pure function :

assume import React, { useReducer, useCallback } from 'react'

1. External function (doc style)

const reducer = (state, action) => state
const MyComp = () => {
  const [state, dispatch] = useReducer(reducer, {})
}

2. useCallback declaration

const MyComp = () => {
  const reducer = useCallback((state, action) => state, [])
  const [state, dispatch] = useReducer(reducer, {})
}

3. useCallback inline declaration alternative

const MyComp = () => {
  const [state, dispatch] = useReducer(useCallback((state, action) => state, []), {})
}

4. inline function declaration

const MyComp = () => {
  const [state, dispatch] = useReducer((state, action) => state, {})
}

Note: readability is a concern of course but I don't need this argument here :)

All this ways "works" and I can't see overly function re-declaration. But I wonder why not the react documentation not describe the 2. useCallback way that if find it cleaner.


Solution

  • I prefer the first approach.

    It's the simplest and it's very unlikely you run into any perf issues.

    React core team themselves warn against premature optimization. using useCallback where it's not needed is a premature optimization and add unnecessary complexity.

    About inline functions: I (and many devs I know) don't approve of inline functions like (approach 3 or 4). it's not a big deal but it's not "clean".