Business
Jobs
  • About Us
  • Solutions
    • Job Postings
      Post your job and receive qualified candidates in 48h.
    • Candidate Assessments
      500+ technical and psychological tests, plus anti-fraud.
    • Headhunting
      Tailor-made executive search from start to finish.
    • Payroll + EOR
      Payroll dispersal and EOR across 15+ LATAM countries.
  • Pricing
  • Jobs

0

139
Views
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 answers
Answer question

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 Report
Answer question
Find remote jobs

Discover the new way to find a job!

Top jobs
Top job categories
Business
Post vacancy Pricing Sales
Legal
Terms and conditions Privacy policy
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Show me some job opportunities
There's an error!