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'
const reducer = (state, action) => state
const MyComp = () => {
const [state, dispatch] = useReducer(reducer, {})
}
useCallback
declarationconst MyComp = () => {
const reducer = useCallback((state, action) => state, [])
const [state, dispatch] = useReducer(reducer, {})
}
useCallback
inline declaration alternativeconst MyComp = () => {
const [state, dispatch] = useReducer(useCallback((state, action) => state, []), {})
}
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.
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".