V
V
Vann Damm2020-05-13 21:45:04
JavaScript
Vann Damm, 2020-05-13 21:45:04

What is useCallback for in this example?

There is a useHttp hook - it has a request function, which describes the logic for receiving data from the server. And it is also wrapped in useCallback.
Hook Code

import {useState, useCallback} from 'react'

export const useHttp = () => {
  const [loading, setLoading] = useState(false)
  const [error, setError] = useState(null)

  const request = useCallback(async (url, method = 'GET', body = null, headers = {}) => {
    setLoading(true)
    try {
      if (body) {
        body = JSON.stringify(body)
        headers['Content-Type'] = 'application/json'
      }

      const response = await fetch(url, {method, body, headers})
      const data = await response.json()

      if (!response.ok) {
        throw new Error(data.message || 'Что-то пошло не так')
      }

      setLoading(false)

      return data
    } catch (e) {
      setLoading(false)
      setError(e.message)
      throw e
    }
  }, [])

  const clearError = useCallback(() => setError(null), [])

  return { loading, request, error, clearError }
}

hook usage code
const {loading, request, error, clearError} = useHttp()

As I understand it, useCallback is used to wrap events and keep a link to them after re-rendering and, accordingly, remove the handler when the component is unmounted. But why wrap request in useCallback in this example? As the author says, so that react does not enter the recursion. But how can he enter it? Explain in more detail what is really happening?

Answer the question

In order to leave comments, you need to log in

1 answer(s)
M
Mikhail Osher, 2020-05-13
@effect_tw

Hook change = component render. If you do not replace the result, then there will be an additional render call.

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question