简体   繁体   中英

What is the right way to use the useCallback hook?

I have an custom input component, like so:

import React, { useState, useCallback } from 'react'

function MyCustomInput ({value: initialValue = '0'}) {
  const [value, setValue] = useState(initialValue)

  const handleChange = useCallback(
    value => {
     setValue(value)
    },
    [setValue]
  )

  return (
    <SomeInputComponent onChange={handleChange}/>
  )
}

The useCallback implementation in React doc says:

const memoizedCallback = useCallback(
  () => {
    doSomething(a, b);
  },
  [a, b]
)

Now as per the doc implementation, the correct way should be:

const handleChange = useCallback(
   value => {
     setValue(value)
   },
   [value] // And not, [setValue]
 )

But this would make the use of useCallback worthless as handleChange would start to get a new func reference each time the value state updates which would lead to unnecessary rerender of my <SomeInputComponent> component. Is my implementation incorrect?

You should include everything that is needed to create the function, the value is passed as a normal parameter when the function is called.

The only dependency needed to build the function in this case is setValue :

const handleChange = useCallback(
  value => {
    setValue(value)
  }, [setValue]
)

However, since setState , dispatch (from useReducer ), and useRef are known to be static, you can omit them from the list of dependencies. The exhaustive-deps rule has a function isDefinitelyStaticDependency(reference) that looks for and "approves" this functions as static. So your code should be:

const handleChange = useCallback(
  value => {
    setValue(value)
  }, []
)

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM