mr.bjerre
mr.bjerre

Reputation: 2888

Using array of custom hooks in react

I've made a custom react hook useMyElement that returns a JSX.Element and some value, i.e.

interface HookOutput {
  element: JSX.Element;
  value: any;
}

This works just fine but now I want to use a list of those elements and values, i.e.

const hookElements = listOfArgs.map(args => useMyElement(args))

but I realize that this is gives unintended usage. I also get the following warning

React Hook "useMyElement" cannot be called inside a callback. React Hooks must be called in a React function component or a custom React Hook function. (react-hooks/rules-of-hooks)

How can I achieve a pattern like this? I.e. want to create a list of react components and return their stateful values from it as well without using something like redux.

Upvotes: 0

Views: 1938

Answers (1)

nightElf
nightElf

Reputation: 522

In this case, firstly, I would make a small change in the 'useMyElement' hook. The interface for HookOutput would look like this:

interface HookOutput {
    elements: JSX.Element[];
    values: any[];
  }

The hook will expose the array of elements and its corresponding values instead of exposing single element and its value.

Now, the hook would look something like this:

const useMyElements = (args: any[]): HookOutput => {
    const [elements, setElements] = useState<JSX.Element[]>([]);
    const [values, setValues] = useState<any[]>([]);

    useEffect(() => {
        args.map(arg => {
            // initialize elements and values
        })
    }, [])

    return {
        elements,
        values
    }
}

I was not sure about the type of args that you would be providing, so, its upto you to initialize the list of elements from the args.

Upvotes: 2

Related Questions