Skip to content

How could we handle expensive or frequent subscriptions that need to access some changing prop/state with hooks? #2862

Description

@infinnie

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.

Metadata

Metadata

Assignees

No one assigned

    Labels

    No labels
    No labels

    Type

    No type

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions