Empresas
Empleos
  • Sobre nosotros
  • Soluciones
    • Publicación de vacantes
      Publica tu vacante y recibe candidatos calificados en 48h.
    • Evaluación de candidatos
      500+ pruebas técnicas y psicológicas, más anti-fraude.
    • Headhunting
      Búsqueda ejecutiva a la medida de principio a fin.
    • Nómina + EOR
      Dispersión de nómina y EOR en más de 15 países de LATAM.
  • Precios
  • Empleos

0

147
Vistas
Wrap function in useCallback

In the code snippet below, I'd like to move this function out of jsx and wrap into useCallback.

{suggestedTags.length ? (
          <div className={classes.tagSuggestionWrapper}>
            {suggestedTags.map((tag) => {
              return (<div key={tag} 
                          onClick={() => { selectTag(tag) }}>{tag}</div>
                          );            
            })}
          </div>
        ) : null }

Otherwise, a new function is created for every element on every render.

I understand that this may complicate the code, and may not be advisable. But I have to do it. I ask for your advice

about 4 years ago · Juan Pablo Isaza
1 Respuestas
Responde la pregunta

0

You can do:

 const selectTag = useCallback((tag) => {
      setTags((prevState) => [...prevState, tag]);
      setSuggestedTags([]);
      setInput("");
    }, [])

Little about useCallback

Bare in mind that if you had used any state variable, or prop, you should have included that in the dependency array. An empty dependency array makes sure selectTag reference will stay the same once the component mounts.

And no dependency array is the same as not using useCallback at all

Removing the arrow function

You can remove the arrow function by passing the value by using the onClick event function:

   const selectTag = (event) => {
      const tag = event.target.name
      setTags((prevState) => [...prevState, tag]);
      setSuggestedTags([]);
      setInput("");
    }

    return (
      
        {suggestedTags.length ? (
              <div className={classes.tagSuggestionWrapper}>
                {suggestedTags.map((tag) => {
                  return (<div key={tag}
                              name={tag}
                              className={classes.tagSuggestion} 
                              onClick={selectTag}>{tag}</div>
                              );            
                })}
              </div>
            ) : null }

      </div>
    );
about 4 years ago · Juan Pablo Isaza Denunciar
Responde la pregunta
Encuentra empleos remotos

¡Descubre la nueva forma de encontrar empleo!

Top de empleos
Top categorías de empleo
Empresas
Publicar vacante Precios Comercial
Legal
Términos y condiciones Política de privacidad
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomiéndame algunas ofertas
Necesito ayuda