Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
1 change: 1 addition & 0 deletions src/hooks/useConditionalEffect/index.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1 @@
export { useConditionalEffect } from './useConditionalEffect.ts';
148 changes: 148 additions & 0 deletions src/hooks/useConditionalEffect/useConditionalEffect.spec.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,148 @@
import { act } from '@testing-library/react';
import { describe, expect, it, vi } from 'vitest';

import { renderHookSSR } from '../../_internal/test-utils/renderHookSSR.tsx';

import { useConditionalEffect } from './useConditionalEffect.ts';

describe('useConditionalEffect', () => {
it('is safe on server side rendering', () => {
const effect = vi.fn();
const condition = vi.fn(() => false);

renderHookSSR.serverOnly(() => useConditionalEffect(effect, [1], condition));

expect(condition).toHaveBeenCalled();
expect(effect).not.toHaveBeenCalled();
});

it('should not run effect when condition returns false', async () => {
const effect = vi.fn();
const condition = vi.fn(() => false);

await renderHookSSR(() => useConditionalEffect(effect, [1], condition));

expect(condition).toHaveBeenCalledWith(undefined, [1]);
expect(effect).not.toHaveBeenCalled();
});

it('should run effect when condition returns true', async () => {
const effect = vi.fn();
const condition = vi.fn(() => true);

await renderHookSSR(() => useConditionalEffect(effect, [1], condition));

expect(condition).toHaveBeenCalledWith(undefined, [1]);
expect(effect).toHaveBeenCalled();
});

it('should warn when an empty dependency array is provided', async () => {
const originalWarn = console.warn;
console.warn = vi.fn();

const effect = vi.fn();
const condition = vi.fn(() => true);

await renderHookSSR(() => useConditionalEffect(effect, [], condition));

expect(console.warn).toHaveBeenCalledWith(
'useConditionalEffect received an empty dependency array. ' +
'This may indicate missing dependencies and could lead to unexpected behavior.'
);

console.warn = originalWarn;
});

it('should run effect multiple times when condition is repeatedly true', async () => {
const effect = vi.fn();
const condition = vi.fn(() => true);

const { rerender } = await renderHookSSR(({ deps }) => useConditionalEffect(effect, deps, condition), {
initialProps: { deps: [1] },
});

expect(effect).toHaveBeenCalledTimes(1);

effect.mockClear();
await act(async () => {
rerender({ deps: [2] });
});

expect(condition).toHaveBeenCalledWith([1], [2]);
expect(effect).toHaveBeenCalledTimes(1);

effect.mockClear();
await act(async () => {
rerender({ deps: [3] });
});

expect(condition).toHaveBeenCalledWith([2], [3]);
expect(effect).toHaveBeenCalledTimes(1);
});

it('should run cleanup function when effect returns one', async () => {
const cleanup = vi.fn();
const effect = vi.fn(() => cleanup);
const condition = vi.fn(() => true);

const { unmount } = await renderHookSSR(() => useConditionalEffect(effect, [1], condition));

unmount();

expect(cleanup).toHaveBeenCalled();
});

it('should store deps for next comparison', async () => {
const effect = vi.fn();
const condition = vi.fn(() => false);

const { rerender } = await renderHookSSR(({ deps }) => useConditionalEffect(effect, deps, condition), {
initialProps: { deps: [1] },
});

expect(condition).toHaveBeenCalledWith(undefined, [1]);

condition.mockClear();

await act(async () => {
rerender({ deps: [2] });
});

expect(condition).toHaveBeenCalledWith([1], [2]);
});

it('should run effect based on conditional logic', async () => {
const effect = vi.fn();

const condition = vi.fn((prev: readonly number[] | undefined, current: readonly number[]) => {
if (prev === undefined) return false;
return current[0] > prev[0];
});

const { rerender } = await renderHookSSR(({ count }) => useConditionalEffect(effect, [count], condition), {
initialProps: { count: 0 },
});

expect(effect).not.toHaveBeenCalled();

effect.mockClear();
condition.mockClear();

await act(async () => {
rerender({ count: 1 });
});

expect(condition).toHaveBeenCalledWith([0], [1]);
expect(effect).toHaveBeenCalled();

effect.mockClear();
condition.mockClear();

await act(async () => {
rerender({ count: 0 });
});

expect(condition).toHaveBeenCalledWith([1], [0]);
expect(effect).not.toHaveBeenCalled();
});
});
70 changes: 70 additions & 0 deletions src/hooks/useConditionalEffect/useConditionalEffect.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,70 @@
import { type DependencyList, type EffectCallback, useCallback, useEffect, useRef } from 'react';

/**
* @description
* `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.
*
* @param {EffectCallback} effect - The effect callback to run.
* @param {DependencyList} deps - Dependencies array, similar to useEffect.
* @param {(prevDeps: T | undefined, currentDeps: T) => boolean} condition - Function that determines if the effect should run based on previous and current deps.
* - On the initial render, `prevDeps` will be `undefined`. Your `condition` function should handle this case.
* - If you want your effect to run on the initial render, return `true` when `prevDeps` is `undefined`.
* - If you don't want your effect to run on the initial render, return `false` when `prevDeps` is `undefined`.
*
* @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>
* );
* }
*
*/
export function useConditionalEffect<T extends DependencyList>(
effect: EffectCallback,
deps: T,
condition: (prevDeps: T | undefined, currentDeps: T) => boolean
): void {
const prevDepsRef = useRef<T | undefined>(undefined);
// eslint-disable-next-line react-hooks/exhaustive-deps
const memoizedCondition = useCallback(condition, deps);

if (deps.length === 0) {
console.warn(
'useConditionalEffect received an empty dependency array. ' +
'This may indicate missing dependencies and could lead to unexpected behavior.'
);
}

const shouldRun = memoizedCondition(prevDepsRef.current, deps);

useEffect(() => {
if (shouldRun) {
const cleanup = effect();
prevDepsRef.current = deps;
return cleanup;
}

prevDepsRef.current = deps;

// eslint-disable-next-line react-hooks/exhaustive-deps
}, deps);
}
1 change: 1 addition & 0 deletions src/index.ts
Original file line number Diff line number Diff line change
Expand Up @@ -4,6 +4,7 @@ export { SwitchCase } from './components/SwitchCase/index.ts';
export { useAsyncEffect } from './hooks/useAsyncEffect/index.ts';
export { useBooleanState } from './hooks/useBooleanState/index.ts';
export { useCallbackOncePerRender } from './hooks/useCallbackOncePerRender/index.ts';
export { useConditionalEffect } from './hooks/useConditionalEffect/index.ts';
export { useControlledState } from './hooks/useControlledState/index.ts';
export { useCounter } from './hooks/useCounter/index.ts';
export { useDebounce } from './hooks/useDebounce/index.ts';
Expand Down
Loading