fix: HMR Break when using context in react templates - Issues: #3301 and #2624#8329
fix: HMR Break when using context in react templates - Issues: #3301 and #2624#8329adnanalbeda wants to merge 1 commit intovitejs:mainfrom
Conversation
When using `createContext` and wrap elements with `context.provided`, hmr breaks and the context tries to access disposed object. This code avoid the problem by creating one react root per model, and it makes loading page faster too.
|
Thanks for the PR. IMO we shouldn't add a workaround in the templates. We should fix the HMR issue. |
|
I don't know how I can exactly investigate the issue. But after I did more work on the project, HMR reloads the whole document after applying this solution and
I know this happens because Vite handles each file alone on calling it, and not as a bundled package. So if I make an edit in Even if its data are coming from the context, if they are passed as props, HMR won't refresh the whole document. |
|
@patak-dev can we merge this as temporary fix, since i research this issue has been persist long time ago, and it affecting the development experience, as we had to manually refresh everytime when we hot reload... |
|
Closing as this is fixed by #10239. |
When using
createContextand 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-viteplugin.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).