Skip to content

Can't perform a React state update on a component that hasn't mounted yet #386

Open
@make-github-pseudonymous-again

Description

In a useTracker-heavy part of my code I got the following warning with React 18 (react-meteor-data v2.6.2):

Warning: Can't perform a React state update on a component that hasn't mounted yet. This indicates that you have a side-effect in your render function that asynchronously later calls tries to update the component. Move this work to useEffect instead.

Not sure if it shows up without <StrictMode/>. If I remember correctly I managed to get the warning both with the deps and no-deps versions of useTracker.

I have not been able to reproduce this behavior in a sandbox yet, and the original code was quite a pain to debug.

I managed to fix it by patching useTracker and useSubscribe to have skipUpdate return true when the component has been initialized but has not mounted yet, using the following hook and have skipUpdate return !hasMounted() || originalSkipUpdate():

import {useRef, useEffect} from 'react';

const useHasMounted = () => {
	const componentWasMounted = useRef(false);

	useEffect(() => {
		componentWasMounted.current = true;
	}, []);

	return () => componentWasMounted.current;
};

export default useHasMounted;

I assume the warning pops up because forceUpdate can be called before an element is mounted now that React can run state code without systematically rendering.

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