Home > Back-end >  Is good to use React.useMemo or React.useCallback inside component props?
Is good to use React.useMemo or React.useCallback inside component props?

Time:11-20

I was thinking about how to code TailwindCSS cleaner in React. Since Tailwind is utility-first, it makes us inevitably end up with components (ex: className="w-full bg-red-500"). So, I tried to create a utility like this:
utils/tailwind.ts

const tw = (...classes: string[]) => classes.join(' ')

and call it inside:
components/Example.tsx

import { useState } from 'react'
import tw from '../utils/tailwind'

const Example = () => {
  const [text, setText] = useState('')

  return (
    <div>
      <input onChange={(e: any) => setText(e.target.value)} />
      <div
        className={tw(
          'w-full',
          'h-full',
          'bg-red-500'
        )}
      >
        hello
      </div>
    </div>
  )
}

But, it will cause tw() to be re-called as always as text state is updated.

So, I decided to wrap tw() function using useMemo to prevent re-call since the tw() always returns the same value. But the code is like this:

import { useState, useMemo } from 'react'
import tw from '../utils/tailwind'

const Example = () => {
  const [text, setText] = useState('')

  return (
    <div>
      <input onChange={(e: any) => setText(e.target.value)} />
      <div
        className={useMemo(() => tw(
          'w-full',
          'h-full',
          'bg-red-500'
        ), [])}
      >
        hello
      </div>
    </div>
  )
}

Is it correct or good practice if I put useMemo like that? Thank you

  • Related