Skip to content

Commit

Permalink
feat: Dependencies inference for useCustomCompareEffect
Browse files Browse the repository at this point in the history
  • Loading branch information
streamich authored Jan 12, 2020
2 parents 4bf9f93 + 091c907 commit 477c164
Showing 1 changed file with 11 additions and 4 deletions.
15 changes: 11 additions & 4 deletions src/useCustomCompareEffect.ts
Original file line number Diff line number Diff line change
Expand Up @@ -2,9 +2,16 @@ import { DependencyList, EffectCallback, useEffect, useRef } from 'react';

const isPrimitive = (val: any) => val !== Object(val);

type DepsEqualFnType = (prevDeps: DependencyList, nextDeps: DependencyList) => boolean;

const useCustomCompareEffect = (effect: EffectCallback, deps: DependencyList, depsEqual: DepsEqualFnType) => {
type DepsEqualFnType<TDeps extends DependencyList> = (
prevDeps: TDeps,
nextDeps: TDeps
) => boolean;

const useCustomCompareEffect = <TDeps extends DependencyList>(
effect: EffectCallback,
deps: TDeps,
depsEqual: DepsEqualFnType<TDeps>
) => {
if (process.env.NODE_ENV !== 'production') {
if (!(deps instanceof Array) || !deps.length) {
console.warn('`useCustomCompareEffect` should not be used with no dependencies. Use React.useEffect instead.');
Expand All @@ -21,7 +28,7 @@ const useCustomCompareEffect = (effect: EffectCallback, deps: DependencyList, de
}
}

const ref = useRef<DependencyList | undefined>(undefined);
const ref = useRef<TDeps | undefined>(undefined);

if (!ref.current || !depsEqual(deps, ref.current)) {
ref.current = deps;
Expand Down

0 comments on commit 477c164

Please sign in to comment.