How to fix eslint warning warning JSX attribute values should not contain functions created in the same scope react-perf/jsx-no-new-function-as-prop

Viewed 33

i am new to programming and learning typescript and i have been trying to understand and fix the eslint warning. i have code like below,

const handleRequestDelete = async () => { //eslint warning
    try {
        await deleteSomething({ variables: { ids }});
  
        onSuccess();
    } catch (error) {
        const [{ status, title, description }] =
        apolloErrorToNotifications(error);
        onError(error);
        throw error;
    }
};

on line const handleRequestDelete it throws eslint warning like so.

warning  JSX attribute values should not contain functions created in the same scope  react-perf/jsx-no-new-function-as-prop

how could i fix this error. could someone help me. thanks.

1 Answers

That lint rule is pointing out that handleRequestDelete will be created new on every render. To satisfy the lint rule, you'll need to wrap your function in useCallback:

const handleRequestDelete = useCallback(
  async () => {
    try {
      await deleteSomething({ variables: { ids } });

      onSuccess();
    } catch (error) {
      const [{ status, title, description }] =
        apolloErrorToNotifications(error);
      onError(error);
      throw error;
    }
  },
  [/* insert dependencies here */]
);

By doing this, then as long as the dependency array doesn't change, you'll reuse the same function on each render. I'm not exactly sure what the dependency array needs to contain, but my guess is [deleteSomething, onSuccess, apolloErrorToNotifications, onError]

If you don't find this lint rule useful, you can disable it in your .eslint.json file, by adding this to the rules section:

"rules": {
  "react-perf/jsx-no-new-function-as-prop": "off"
}
Related