FAQ ‐ Code Edition - Dadarkp3/pokedex GitHub Wiki

Explaning a few code decisions related to the project

Why useCallback?

In the code of our useSearchPokemon useCallback is used to memoize the fetchPokemon function. Let's explore why it's beneficial to use useCallback in this case

Preventing Unnecessary Re-renders

  • Without useCallback, each time the usePokemonSearch hook is called, a new instance of the fetchPokemon function would be created.
  • This could potentially lead to unnecessary re-renders of components that depend on this function, as they would be treated as different functions every time.
  • By using useCallback, the function reference remains constant as long as its dependencies (query and oldQuery) remain unchanged.
  • This ensures that components relying on this function are not re-rendered unnecessarily.

Optimizing Performance

  • Since fetchPokemon is an asynchronous function that triggers data fetching, memoizing it with useCallback prevents unnecessary re-execution of the function when its dependencies (query and oldQuery) haven't changed.
  • This can lead to performance optimizations, especially in scenarios where the function is called frequently or in response to user interactions.

Avoiding Infinite Loops

  • In the useEffect hook, fetchPokemon is included as a dependency. Without useCallback, the fetchPokemon function reference would change on each render, causing the useEffect hook to run on every render.
  • This could potentially lead to infinite loops, as the fetchPokemon function itself triggers a state update, causing a re-render and re-execution of the useEffect hook.
  • By memoizing fetchPokemon with useCallback, its reference remains stable, preventing unintended re-executions of the useEffect hook.

Conclusion

Using useCallback in this case ensures that the fetchPokemon function remains memoized with stable references, preventing unnecessary re-renders, optimizing performance, and avoiding potential infinite loops in the useEffect hook.


Why use Next.js Route API