Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Why my useCallback() is rerender evey time?

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 :

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

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

>Solution :

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.

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading