Issue
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.
Solution
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} />;
}
Answered By - Samson
Answer Checked By - - Clifford M. (ReactFix Volunteer)