DEV Community

Cover image for ReactJS Anti Pattern ~use hook in the client component~
Ogasawara Kakeru
Ogasawara Kakeru

Posted on

ReactJS Anti Pattern ~use hook in the client component~

・This code illustrates how to use the use hook to create and resolve a Promise in the client component.

'use client'

import { Suspense, use } from 'react'

const getName = async () => {
  await new Promise((resolve) => setTimeout(resolve, 3000))

  const randomName =
    Math.random().toString(36).substring(2, 7) +
    Math.random().toString(36).substring(2, 7)

  return randomName
}

const Hoge = () => {
  console.log('render')
  const name = use(getName())

  return <Suspense fallback={<div>loading...</div>}>{name}</Suspense>
}

export default Hoge
Enter fullscreen mode Exit fullscreen mode

If you create and resolve the Promise by using the use hook in the client component, the result will be:

1.Create Promise.

2.Resolve the Promise using the use hook.

3.Rendering occurs.

4.The Promiseis created because of the client component.

5.The Promise is resolved by the use hook.

6.Rendering occurs.

continues...

As a result, infinite rendering occurs.

Top comments (0)