Next.js Discord

Discord Forum

useCallback vs not

Unanswered
British Shorthair posted this in #help-forum
Open in Discord
British ShorthairOP
useCallback still computes whatever is inside, but saves its memory reference so it does not have to re-create again if props have not changed.

So given that setData uses itself (not calling data state value) to spread in previous items, using a useCallback here won't do anything because React will memoize the function itself.

Now because I am calling it within a prop, if for some reason fetchData reference changes, then React will flag SomeComponent for a re-render.

If I am thinking about this correctly, then if React will memoize the fetchData function by itself, then a useCallback won't do anything?

  const [data, setData] = useState(initialData)

  const fetchData = async () => {
    try {
      const response = fetch(...)
      const data = await response.json()

      setData(prev => ({
        params: data.params,
        results: [...prev.results, ...data.results]
      }))
    } catch () {
      ...
    }
  }

  <SomeComponent onScrollEnd={end => {
    if (!isFetching && end) {
      fetchData()
    }
  }}>
    {data.map(...)}
  </SomeComponent>

0 Replies