skip to Main Content

I’m trying to load data for a client component. I can’t use await/async as specified by React’s RFC about use() hook. Thus I need to use use() hook.

However, it goes into infinite loop.

Here’s my code:

import { use } from 'react'

const Component = () => {

    const response = use(fetch('some_url'))
    const data = use(response.json())

    return <div>{data}</div>
}

Based on my intuition, I tried to use a callback inside the use() hook, as we do for useEffect():

const response = use(() => fetch('use_url'), [])

But it complained that an invalid parameter is passed into the use() hook.

I can’t find anyting online. What should I do? What have I done wrong?

2

Answers


  1. You need to "stabilize" the return of fetch. You could memoize it

    const Component = () => {
      const fetchPromise = React.useMemo(() => fetch('some_url').then(r => r.json()), [])
      const data = use(fetchPromise);
    
      return <div>{data}</div>;
    }
    
    Login or Signup to reply.
  2. I guess you just wanna memorized use result.

    const response = useMemo(() => use(use(fetch('some_url')).json()), ['some_deps'])
    
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search