Skip to content

Latest commit

 

History

History
68 lines (54 loc) · 1.86 KB

File metadata and controls

68 lines (54 loc) · 1.86 KB

useConditionalEffect

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.

Interface

function useConditionalEffect(
  effect: EffectCallback,
  deps: DependencyList,
  condition: (prevDeps: T | undefined, currentDeps: T) => boolean
): void;

Parameters

Return Value

This hook does not return anything.

Example

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>
  );
}