0

I'm struggeling already some days now. I'm searching for a way to define a React component without UI. My goal is to have several functions in one "component" (as I said without UI), which can be used by other components, but with all the benefits of useState etc. I already, thought, there is a way, by defining components like this:

export const useExample = () => {
    const [someVariable, setSomeVariable] = useState('someValue');

    const getSomething = (parameter1, parameter2) => {
        return ...
    }

    return {
        getSomething
    };
}

I thought, I could import useExample in a component and then use the function getSomething like this:

import { useExample } from 'useExample.component.js';
//...

function SomeComponent(props) {
    //...
    useEffect(() => {
        const example = useExample.getSomething(parameter1, parameter2);
    },[]);
    //...
}

...but actually this seems not be working.

Then I get an error like this:

Uncaught TypeError:

...useExample.getSomething is not a function at eval...

All docs I find is telling me, that I need to return a JSX element. But I really cannot believe that in React there is no way to do this. Am I wrong? I know, if I use plain JS, I'm able to do so, but I already tried this approach and there are many other difficulties then with combining it with React components. Did anyone have had a similar issue and found a solution to this?

dns_nx
  • 3,651
  • 4
  • 37
  • 66
  • useExample is a function, this function does not has a prototype like an object. I see that you tried to call like a object. Do you need a function or object? Because getSomething always work in useExample. It is not a prototype, it's a function in useExample. Change your mind. – ht13 Jul 24 '22 at 19:48
  • https://stackoverflow.com/questions/1592384/adding-prototype-to-javascript-object-literal you can check this approach. – ht13 Jul 24 '22 at 19:50
  • Actually I need an object. As I wrote my first tries have been with standard classes of JS and creating instances of these classes. That worked fine until a certain step. – dns_nx Jul 24 '22 at 19:57

1 Answers1

2

What you're trying to create is a custom hook, not a component.

You cannot call a hook in a useEffect, but since it returns an object containing the function, you can store this function in a variable and then call it in the useEffect.

function SomeComponent(props) {
    const { getSomething } = useExample();

    useEffect(() => {
        const example = getSomething(parameter1, parameter2);
    },[]);

    //...
}

Also be aware that if you call this function in the useEffect, you probably want to put it in the dependency array. And depending on the rest of your code, it also means you might need to wrap getSomething in a useCallback.

Arkellys
  • 5,562
  • 2
  • 16
  • 40