Raven
Raven

Reputation: 699

How to make a custom hook respond to changes in state?

I have a custom hook that processes a certain state variable.

Whenever you change the state It does not update immediately so I have to subscribe to it using useEffect.

However it is categorically impossible to call a custom hook within useEffect.

How does one get their custom hooks to do anything at all with a state variable?

Upvotes: 4

Views: 8124

Answers (1)

kca
kca

Reputation: 6121

You can not (should not) call a custom hook inside of useEffect, but you can use useEffect inside of your custom hook:

const useMyHook = function( someState ){
    useEffect( function(){
        // do what the hook should do
    }, [ someState ]);
};

If the hook should update also when something else changes, you can just pass that as well:

const useMyHook = function( someState, someDependency ){
    useEffect( function(){
        // do what the hook should do
    }, [ someState, someDependency ]);
};

I suggest to use an array for the dependencies, so that it works similar to useEffect:

const useMyHook = function( label, dependencies ){

    const [ value, setValue ] = useState(0);

    useEffect( function(){
        setValue( value + 1 );
    }, [ label, ...dependencies ]);

    return label + ': ' + value;
};

// ...

const value = useMyHook('counter', [ dependentValue, otherDependentValue ]);

Upvotes: 5

Related Questions