Home > Software engineering >  How to make a generic callback function react
How to make a generic callback function react

Time:09-24

I am creating a callback function for passing setState up from child to parent. However, I have found myself creating tonnes of functions for each type of state im using and was wondering if there would be a way to make this generic. Here is an example of one of the functions:

    const setIsModalVisible = useCallback(val => {
    setModalVisible(val);
  }, [setModalVisible]);

Each function is the same but using a different setState. Any help would be great! Thanks

CodePudding user response:

Create a function which returns callback

const GetCallback = (func) => {
    return useCallback(
        (val) => {
          func(val);
        },
        [func]
    );
};

and call that function by passing the setState as a argument.

CodeSandbox Link - https://codesandbox.io/s/quiet-lake-h2pzr?file=/src/App.js

CodePudding user response:

React hooks (so useCallback too) must be used in root of the component function. Therefore You cannot make some generator for creating multiple useCalback.

  • Related