1 of 14

useEffect &

async/await & fetch

2 of 14

01

02

03

04

05

06

Previously on React

useEffect

Timeout!

Break!

async/await a little more

Playing fetch

10 min

20 min

15 min

10 min

30 min

20 min

3 of 14

01 Previously on React

4 of 14

02 useEffect

5 of 14

useEffect(setup, [dependencies])

  • A hook that lets you synchronize a component with an external system
  • setup gets called to set up the synchronization, and optionally return a cleanup callback
  • dependencies is an optional list of values that, once changed, trigger setup to be called again

Docs: React.dev

6 of 14

03 Timeout!

7 of 14

setTimeout/setInterval usage in useEffect

useEffect(() => {

const handle = setTimeout(callback, ms)

return () => clearTimeout(handle)

})

  • useEffect() can apply a cleanup function once the component is “unmounted”
  • Avoids leakages or troubles with long-running processes

8 of 14

9 of 14

Break!

10 of 14

04 async/await a little more

11 of 14

async/await

  • Things happening at different paces and finishing in different moments
  • Synchronous JS needs to keep track of everything happening
  • Promises (.then()) are one of the ways to “sequence” things while keeping code “synchronous”
  • async/await makes the sequence more natural

Demo

Docs: MDN

12 of 14

05 Playing fetch

13 of 14

await fetch(url, {options})

  • fetch() makes HTTP/HTTPS requests, and is asynchronous
  • url is the endpoint of the request
  • options is an object that contains the parameters for the request:
    • method: “GET”/“POST”/“PUT”/“DELETE” etc.
    • mode: “cors”/“no-cors”/“same-origin”
    • headers:
      • Content-Type: the MIME type of the request�(usually “application/json”, default “application/x-www-form-urlencoded”)
    • body: the data of the request

14 of 14