-
Notifications
You must be signed in to change notification settings - Fork 2.8k
chore: enhance useTrackedEffect type #2196
New issue
Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.
By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.
Already on GitHub? Sign in to your account
Conversation
wei.xue seems not to be a GitHub user. You need a GitHub account to be able to sign the CLA. If you have already a GitHub account, please add the email address used for this commit to your account. You have signed the CLA already but the status is still pending? Let us recheck it. |
I find a better way to do this: import type { DependencyList } from 'react';
import { useEffect, useRef } from 'react';
- type Effect<T extends unknown[]> = (
+ type Effect<T extends DependencyList> = (
changes?: number[],
- previousDeps?: [...T],
+ previousDeps?: T,
- currentDeps?: [...T],
+ currentDeps?: T,
) => void | (() => void);
const diffTwoDeps = (deps1?: DependencyList, deps2?: DependencyList) => {
//Let's do a reference equality check on 2 dependency list.
//If deps1 is defined, we iterate over deps1 and do comparison on each element with equivalent element from deps2
//As this func is used only in this hook, we assume 2 deps always have same length.
return deps1
? deps1
.map((_ele, idx) => (!Object.is(deps1[idx], deps2?.[idx]) ? idx : -1))
.filter((ele) => ele >= 0)
: deps2
? deps2.map((_ele, idx) => idx)
: [];
};
- const useTrackedEffect = <T extends unknown[]>(effect: Effect<T>, deps?: [...T]) => {
+ const useTrackedEffect = <T extends DependencyList>(effect: Effect<T>, deps?: [...T]) => {
const previousDepsRef = useRef<T>();
useEffect(() => {
const changes = diffTwoDeps(previousDepsRef.current, deps);
const previousDeps = previousDepsRef.current;
previousDepsRef.current = deps;
return effect(changes, previousDeps, deps);
}, deps);
};
export default useTrackedEffect; I think the built-in type |
@liuyib This seems to be more accurate 👍 |
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
Nice work, thx
@liuyib need merge. |
🤔 This is a ...
🔗 Related issue link
fix: #2195
💡 Background and solution
#2195
📝 Changelog
☑️ Self Check before Merge