Home > OS >  Why my useCallback() is rerender evey time?
Why my useCallback() is rerender evey time?

Time:12-14

I read some tutorials on useCallback(), including this one: https://www.youtube.com/watch?v=wNX5iRhczHM I'm sorry, it's in French.

In the tutorials, useCallbacks are only executed once (usually a console.log() is present to demonstrate this)

I tried a very simple example, but I don't understand why my useCallback (constant header()) is rerun every time I press "Increment": I have a console.log each time while I wish it only once :

const IndexScreen = () => {
  const [count, setCount] = useState(1)

  const header = useCallback(
    () => {
      console.log('execute header')

      return (
        <Text>
          Header
        </Text>
      )
     },
    []
  )

  return (
    <View>
      {header()}
      <Button onPress={() => setCount(count   1)} title="Increment" />
      <Text>
        {count}
      </Text>
    </View>
  )
}

Thanks you very much

CodePudding user response:

useCallback is used if you want to memoize a function and use it either as dependency or pass it to a child component. This hook makes sure that you get same reference for a function if nothing changed from dependencies.

When your component renders header() is a function that will be called every time. And that is expected. What you potentially want is useMemo to prevent triggering of that part of your code every time your component is rerendered:

const IndexScreen = () => {
  const [count, setCount] = useState(1)

  const header = useMemo(
    () => {
      console.log('execute header')

      return (
        <Text>
          Header
        </Text>
      )
     },
    []
  )

  return (
    <View>
      {header}
      <Button onPress={() => setCount(count   1)} title="Increment" />
      <Text>
        {count}
      </Text>
    </View>
  )
}

useMemo should be used rarely since that is an optimization of any hard calculating operation or something that you don't want to be run on every render.

CodePudding user response:

Since I don't speak French I cant say much about the tutorial. Sorry :) But I think I can still help you with your example:

Think of useCallback as a way to define (more precisely to memoize) a function. In your example this is indeed only done once.

However, the function itself (() => console.log() ....) can be executed at any time and as many times as you want by calling it with header().

In you example, since header() is part of the return statement it is called every time the component re-renders, e.g. every time it's state changes, e.g. every time setCounter changes the counter.

  • Related