DEV Community

chantastic
chantastic

Posted on

Skip React.useEffect by Providing an Inputs Array

By default, React.useEffect runs every time that component renders.

When we combine React.useEffect and React.useState to fetch and update our component with state, we create an infinite fetching loop:

React.useEffect(() => {
  fetchPokemon(index).then(pokemon => setPokemon(pokemon));
})
Enter fullscreen mode Exit fullscreen mode

Our app will keep fetching and updating and fetching again until the we close the page.

React gives us a way to "skip" useEffect Hooks by tracking inputs.
We track inputs by giving useEffect an array as a second argument.

React.useEffect(func, [])

This array will contain the inputs we want to observe for changes.
React will "skip" useEffect calls where inputs haven't changed.

You can think about it like this:

React.useEffect(func)          // Every render
React.useEffect(func, [])      // First render
React.useEffect(func, [index]) // First and every time `index` changes
Enter fullscreen mode Exit fullscreen mode

When we update our React.useEffect Hook to "skip" when index hasn't changed, we ensure that we only make fetch requests when we get a new index.

function usePokemon(index) {
  let [pokemon, setPokemon] = React.useState(null);

  React.useEffect(() => {
    fetchPokemon(index).then(json => setPokemon(json));
- });
+ }, [index]);

  return pokemon;
}
Enter fullscreen mode Exit fullscreen mode

Assignment CodeSandbox:

Assignment

Restrict redundant useEffect calls by supplying the inputs argument

  1. Pass an empty array ([]) to React.useEffect as the second argument
  2. Click the next button a few times. Notice how it no longer updates the Pokemon?
    • This array holds values that we'd like to track for changes. Where, before, React was calling useEffect every time this function is called, it now runs only the first time it's called.
  3. Add index to the inputs array to be tracked for changes

Subscribe on YouTube:

Follow the ๐Ÿงต on Twitter:

Top comments (0)