fix: HMR Break when using context in react templates - Issues: #3301 and #2624 #8329
Add this suggestion to a batch that can be applied as a single commit.
This suggestion is invalid because no changes were made to the code.
Suggestions cannot be applied while the pull request is closed.
Suggestions cannot be applied while viewing a subset of changes.
Only one suggestion per line can be applied in a batch.
Add this suggestion to a batch that can be applied as a single commit.
Applying suggestions on deleted lines is not supported.
You must change the existing code in this line in order to create a valid suggestion.
Outdated suggestions cannot be applied.
This suggestion has been applied or marked resolved.
Suggestions cannot be applied from pending reviews.
Suggestions cannot be applied on multi-line comments.
Suggestions cannot be applied while the pull request is queued to merge.
Suggestion cannot be applied right now. Please check back later.
When using
createContext
and wrap elements withcontext.provider
, hmr breaks and the context tries to access disposed object.This new template avoid the problem by creating one react root per model, and it makes loading page faster too.
Description
HMR breaks in react templates when using contexts and wrap the
<App />
with any context provider.I found this error in console:
so it seems that in the current template, the root is being recreated with each Hot Reload leading to the dispose of old one, which made contexts stores throw
can't access lexical declaration 'SomeContext' before initialization
.So the new main.jsx and main.tsx address this problem in general.
It makes sure that the root is created only once.
I also noticed pages are loading faster after using this method.
BTW, the react error appears in the console anyway after each Hot Reload, whether using context or not.
Additional context
This PR for the new template is a work around for issues #3301 and #2624.
It doesn't doesn't address the problem itself in the
react-vite
plugin.Even though the problem doesn't persist, this solution creates a new issue.
The context resets with every new change, which means it loses all its data;
but still better than just seeing an empty white screen.
So until the issue is fixed in the plugin, this workaround does the job.
What is the purpose of this pull request?
Before submitting the PR, please make sure you do the following
fixes #123
).