What's the use of userCallback in reactJS

I’ve read the documentation and went through some tutorials but I still don’t understand why we use useCallback Hook.

  const fetchData = ()=>{
    fetch(github.baseURL, {
      method: "POST",
      headers: github.headers,
      body: JSON.stringify(query)
    })
    .then(res => res.json())
    .then(({data})=> {
      setUserName(data.viewer.name) 
      console.log(data)
    })
    .catch(err => { console.log(err)})
  }
  useEffect(() => { fetchData()})

I understand that the problem with this code is that it renders twice. It renders componentDidMount and the component did update.

If I just add an empty array it fixes the problem.

useEffect(() => { fetchData()}, [])

And I understand why that is, if I had a state value, I would say run this effect when that particular value changes, since the away is empty it runs only on mount.

The course I’m going through says to do use useCallback

  const fetchData = useCallback(()=>{
    fetch(github.baseURL, {
      method: "POST",
      headers: github.headers,
      body: JSON.stringify(query)
    })
    .then(res => res.json())
    .then(({data})=> {
      setUserName(data.viewer.name) 
    })
    .catch(err => { console.log(err)})
  }, [])
  
  useEffect(() => {    fetchData()  }, [fetchData])

I don’t understand why.

Is there an easy explanation?

While I don’t know much about React, I’ve found that the following article helps to explore and explain this particular issue.

This topic was automatically closed 91 days after the last reply. New replies are no longer allowed.