Answer the question
In order to leave comments, you need to log in
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 }
}
const {loading, request, error, clearError} = useHttp()
Answer the question
In order to leave comments, you need to log in
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 questionAsk a Question
731 491 924 answers to any question