简体   繁体   中英

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

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>
    );

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM