Skip to main content

useConditionalEffect

A custom hook that runs an effect only when the given condition is true.

It checks the condition whenever the dependency array changes, and runs effectCallback when the condition is true.

The condition can be passed as a boolean value or a function. When passed as a function, it receives the previous dependency array (prevDeps) and the current dependency array (currentDeps) as arguments, allowing for more fine-grained condition evaluation.


Code

🔗 View source code


Interface

typescript
function useConditionalEffect<D extends DependencyList>(
effectCallback: EffectCallback,
deps: D,
condition: boolean | ((prevDeps: D | undefined, currentDeps: D) => boolean)
): void

Parameters

NameTypeDescription
effectCallbackEffectCallbackThe effect function to execute
depsDDependency array
conditionboolean | ((prevDeps: D | undefined, currentDeps: D) => boolean)The condition to run the effect. A boolean or a function receiving previous and current dependency arrays

Usage

typescript
import { useConditionalEffect } from '@modern-kit/react'

const Example = () => {
const [count, setCount] = useState(0);
const [message, setMessage] = useState('');

useConditionalEffect(() => {
setMessage(`count is greater than 5! (current: ${count})`);
}, [count], count > 5);

return (
<div>
<p>Count: {count}</p>
<button onClick={() => setCount(count + 1)}>Increment</button>
<button onClick={() => setCount(count - 1)}>Decrement</button>
<p>{message}</p>
</div>
);
}

Example

Count: 0

⏳ count is 5 or below