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

Open
#386 6 comments 1 reaction 0 assignees View on GitHub

Nobody has claimed this yet.

Assessment

Difficulty
3/5
Estimated time
1-2 days
Newbie friendliness
35/100
Issue type
Bug
Clarity
Needs clarification
Activity status
Stale
Tech stack
javascript, react
Domain
frontend

Research direction

Start by examining the useTracker and useSubscribe hooks, especially their skipUpdate handling, and reproduce the warning with React 18 and StrictMode if possible. Done means confirming that state updates do not trigger the pre-mount warning in the affected hooks.

Written by the indexing model from the issue text.

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.

Dominant language
JavaScript
Stars
576
Forks
168
Avg merge
4d 3h
Merged PRs (30d)
1

Contributor guide

No contributing guide indexed for this repository

First steps

  1. Read the whole issue, then the project's contributing guide.
  2. Comment on the issue to say you are picking it up — it saves two people doing the same work.
  3. Fork the repository and make your change on a branch.
  4. Open a pull request that references the issue number.

More from meteor/react-packages

All issues in meteor/react-packages

Similar issues

More JavaScript issues

Get new issues in your inbox

A short digest of beginner-friendly GitHub issues.