useConditionalEffect is a React hook that conditionally executes effects based on a predicate function. This provides more control over when effects run beyond just dependency changes.
function useConditionalEffect(
effect: EffectCallback,
deps: DependencyList,
condition: (prevDeps: T | undefined, currentDeps: T) => boolean
): void;This hook does not return anything.
import { useConditionalEffect } from 'react-simplikit';
function Component() {
const [count, setCount] = useState(0);
// Only run effect when count increases
useConditionalEffect(
() => {
console.log(`Count increased to ${count}`);
},
[count],
(prevDeps, currentDeps) => {
// Only run when count is defined and has increased
return prevDeps && currentDeps[0] > prevDeps[0];
}
);
return (
<button onClick={() => setCount(prev => prev + 1)}>
Increment: {count}
</button>
);
}