How could we handle expensive or frequent subscriptions that need to access some changing prop/state with hooks?
Open
Nobody has claimed this yet.
- Dominant language
- JavaScript
- Stars
- 11.8k
- Forks
- 7.9k
- Avg merge
- 1d 11h
- Merged PRs (30d)
- 11
Description
It sort of looks hard without breaking the rule
const Component = ({ outer }) => {
const [mutable, setMutable] = useState(0);
const [cond, setCond] = useState(false);
useEffect(() => {
const handle = doExpensiveSubscription((value) => {
if (cond) {
// cond and outer are stale values
setMutable(calculate(outer, value));
}
});
return handle.unsubscribe;
// the ESLint exhaustive-deps rule would warn about unmet dependency: outer, cond
}, []);
return <div onClick={() => setCond(!cond)}>{mutable}</div>;
};
My temporary solution to the problem looks like
const Component = ({ outer }) => {
const [mutable, setMutable] = useState(0);
const [cond, setCond] = useState(false);
const paramRef = useRef({});
paramRef.current = { outer, cond };
useEffect(() => {
const handle = doExpensiveSubscription((value) => {
const { outer, cond } = paramRef.current;
if (cond) {
// cond and outer hold their respective current values now
setMutable(calculate(outer, value));
}
});
return handle.unsubscribe;
// the ESLint exhaustive-deps rule would warn about unmet dependency: outer, cond
}, []);
return <div onClick={() => setCond(!cond)}>{mutable}</div>;
};
There does not seem to be a specific documentation about that.
Contributor guide
First steps
- Read the whole issue, then the project's contributing guide.
- Comment on the issue to say you are picking it up — it saves two people doing the same work.
- Fork the repository and make your change on a branch.
- Open a pull request that references the issue number.
Research direction
Start with the hooks examples in the issue and review the existing documentation for useEffect, useRef, and exhaustive-deps. Determine how the documentation should explain subscriptions that need current props or state without recreating expensive subscriptions; done when the guidance addresses the stale-value problem and the dependency warning.
Written by the indexing model from the issue text.
Assessment
- Tech stack
- javascript, react
- Domain
- documentation
- Issue type
- Documentation
- Difficulty
- 4/5
- Estimated time
- 3-5 days
- Activity status
- Stale
- Clarity
- Mostly clear
- Newbie friendliness
- 35/100