API calls with JS and useEffect

@salman_arfat

Prerequisites

  • >= JS ES6
  • Basic Knowledge about APIs
  • Basic knowledge of React
    • Functional Components
    • useState

We'll not learn

  • How to make APIs
  • How React (at a very basic level) works

New ticket!

Add an input through which the users can search a database of cities.

  • The API is exposed through a function `getCities` of the following signature.
    • getCities(query: string) => Promise(string[])
      

 

Note

First try

Write the data fetching logic in the component itself

Potential Problems

  • Leads to many unnecessary renders
  • Cannot control when the API fetching should stop
  • Others (render phase should not contain side-effects)

useEffect: fn Hook

What's an effect?

Very simply, an effect is (possible) change in the environment of the program.

  • modifying a non-local variable
  • performing I/O
    • Like making a network request
  • calling other side-effect functions.

}

side effects

useEffect(arg: fn) Hook

Accepts a function that contains imperative, possibly effectful code.

Initial render
Change?
render
Change?
render
Change?
render
Initial render
Change?
Effects
render
Effects?
componentDidMount
componentDidUpdate
Change?
render
Effects?
componentDidUpdate

Second Try

Put the data fetching logic in a useEffect callback

Potential Problems

  • Still leads to many unnecessary renders
  • Still cannot control when the API fetching should stop
  • Others (render phase should not contain side-effects)

Solution? The second argument

https://ncoughlin.com/posts/react-hooks-use-effect/

https://dmitripavlutin.com/react-useeffect-infinite-loop/

Third try

  • Add `[]` to the deps array.
  • Add `query` to the deps array.

Potential Problems

  • No unnecessary renders
  • Can control when the API fetching should stop
  • Others (render phase should not contain side-effects)

More problems?

Multiple in-flight request?

The cleanup function

The function passed to `useEffect` may return a clean-up function.

  • The clean-up function runs before the component is removed from the UI to prevent memory leaks.
  • When a component renders multiple times, the previous effect is cleaned up before executing the next effect.
Initial render
cleanup?
Effects
render
Effects?
componentDidMount
componentDidUpdate
Change?
render
Effects?
componentDidUpdate
Change?
cleanup?
cleanup?
componentWillUnmount

https://tusharsharma.dev/posts/react-hooks-mental-model

Fourth Try

Use the `cleanup` function to invalidate in-flight requests

(is this final?)

API calls with JS and useEffect

By Arfat Salman

API calls with JS and useEffect

  • 488