Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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?

like image 200
Raven Avatar asked Oct 26 '25 06:10

Raven


1 Answers

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 ]);
like image 113
kca Avatar answered Oct 28 '25 20:10

kca



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!