简体   繁体   中英

What is the correct way to pass a function as a Prop in React

There are a few questions with similar wording but none that helps me.

I have a parent component, that wants to pass a function to a child component through Props, and the child component will execute the function within its logic. However, ESLint is returning me the error "JSX props should not use functions react/jsx-no-bind ". I understand that this is inefficient because the function will be re-created everytime the component re-renders. What would be the correct way to do this?

Parent Component

function App() {
  const [recipes, setRecipes] = useState(sampleRecipes);

  function handleRecipeAdd() {
    const newRecipe = // some logic to create newRecipe here
    setRecipes([...recipes, newRecipe]);
    
  }

  return <RecipeList recipes={recipes} handleRecipeAdd={handleRecipeAdd} />;
}

Child Component

interface Props {
  handleRecipeAdd: () => void;
}

export default function RecipeList(props: Props) {
  const { handleRecipeAdd } = props;
  return (
        <button onClick={handleRecipeAdd}>
          Add Recipe
        </button>
  );
}

Note that this is not the exact code for both components, it has been simplified to remove irrelevant code.

Huge thanks to Robin Zigmond for pointing me to the correct place to look at, this has been resolved with the useCallback hook. For anyone who is interested, here's what the updated code looks like:

Parent Component

function App() {
  const [recipes, setRecipes] = useState(sampleRecipes);

  const handleRecipeAdd = useCallback(() => {
    const newRecipe = // some logic to create newRecipe here
    setRecipes([...recipes, newRecipe]);
  }, [recipes]);

  return <RecipeList recipes={recipes} handleRecipeAdd={handleRecipeAdd} />;
}

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