3
头图

join us!

161076dcbcf95a " , to provide front-end developers with technical information and a series of basic articles. For a better user experience, please move to our official website rookies (161076dcbcf962 https://xhs-rookies.com/ ) to learn and get the latest articles in time.

"Code tailor" , if you are interested in our article or want to make some suggestions, follow "Novices of Xiaohe Mountain" , contact us, you can also watch it on WeChat Our article. Every suggestion or approval is a great encouragement to us!

Preface

In this article, our main purpose is to understand the use of (useCallback)

useCallback

definition

useCallback returns a memoized callback function.

const memoizedCallback = useCallback(fn, deps)

useCallback required parameters

  • fn : A function will eventually return the callback function, and the callback function will only be updated when the parameters of deps
  • deps : A list of parameters used to trigger the change of the callback function of fn
Note: deps is an array, that is to say, there can be many parameters to fn

useCallback inline callback function and dependency array as parameters to 061076dcbcfcd8, it will return the memoized version of the callback function, and the callback function will only be updated when a certain dependency changes. It is very useful when you pass callback functions to subcomponents that are optimized and use reference equality to avoid unnecessary rendering (such as shouldComponentUpdate

how to use

Let's first look at a simple example.

This is a child component that accepts a fn method of the parent class and displays its button.

const ChildComponent = memo(function (props) {
  console.log('child render!')
  return <Button onClick={props.fn}> showTime</Button>
})
Note: where memo is also a Hooks . For details, please see Hook API Index – React (reactjs.org)

This is a parent component, which has a counter, a number increase button, and this child component.

function Main() {
  const [count, setcount] = useState(0)

  const ShowTime = () => {
    console.log('now time :' + new Date())
  }

  return (
    <Row
      style={{
        'flex-direction': 'column',
      }}
    >
      <Col>
        <Title>index:{count}</Title>
      </Col>
      <Col>
        <Button onClick={() => setcount(count + 1)}>increase</Button>
      </Col>
      <Col>
        <ChildComponent fn={ShowTime} />
      </Col>
    </Row>
  )
}

We can see that when we click the increase button, count has increased, which is normal and reasonable.

60cv4-43wz0.gif

But at this time, when we open our browser console, we will find that the sub-component ChildComponent in the non-stop render .

This is unreasonable. For us, the subcomponent should only be affected by childname . If the parameter function of fn does not change, we should not go to render .

Note: this place subcomponents kept render reason is that this ShowTime method in constant re-create, and then lead to sub-assemblies passed props in fact is not the same, thus resulting in non-stop render

At this time we used useCallback .

function Main() {
  const [count, setcount] = useState(0)

  const useMemoryCallback = useCallback(() => {
    console.log('now time :' + new Date())
  }, [])

  return (
    <Row
      style={{
        'flex-direction': 'column',
        marginLeft: '10px',
      }}
    >
      <Col>
        <Title>index:{count}</Title>
      </Col>
      <Col>
        <Button onClick={() => setcount(count + 1)}>increase</Button>
      </Col>
      <Col>
        <ChildComponent fn={useMemoryCallback} />
      </Col>
    </Row>
  )
}

At this time, we put this function in useCallback to return, because the deps is empty, so there is no need to change it, so that when we click the increase , we won't trigger the subcomponent's render .

How to check

The dependency array ( deps ) will not be passed as a parameter to the callback function. Although conceptually it appears as: all values referenced in the callback function should appear in the dependency array. In the future, the compiler will be more intelligent, and it will be possible to create an array automatically.

We recommend to enable eslint-plugin-react-hooks in exhaustive-deps rules. This rule will issue a warning when adding a wrong dependency and give repair suggestions.

summary

  • useCallback brings us a memory function. Combining sub-components and useMemo can achieve the effect of optimizing component loading.
  • If the subcomponent accepts a method as an attribute, when we use React.memo avoid unnecessary rendering of the useCallback , we need to use 061076dcbd0816 to cooperate, otherwise React.memo will be meaningless.

Preview of the next section

In the next section, we will introduce you to the hook rule, so stay tuned!


小和山的菜鸟们
377 声望2.1k 粉丝

每日进步的菜鸟,分享前端学习手册,和有心学习前端技术的小伙伴们互相探讨,一同成长。