Oliver Darby
Oliver Darby

Reputation: 544

How to make a generic callback function react

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

Upvotes: 1

Views: 1271

Answers (2)

Tony King
Tony King

Reputation: 61

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

Upvotes: 1

Konrad
Konrad

Reputation: 287

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

Upvotes: 0

Related Questions