ArnaudBarre / eslint-plugin-react-refresh

Validate that your components can safely be updated with Fast Refresh
MIT License
206 stars 13 forks source link

Correct use with Context API and Vite - docs missing? #22

Closed lorand-horvath closed 1 year ago

lorand-horvath commented 1 year ago

I am using the latest Vite for building a React app in which I have a PostsContext.jsx file that exports a custom context provider (component) PostsProvider and custom hook usePosts as named exports:

export {PostsProvider, usePosts}

So this react-refresh eslint plugin immediately warns about exporting multiple values (component and hook in this case).

warning  Fast refresh only works when a file only exports components.
Use a new file to share constants or functions between components

Unfortunately I cannot move each export to a separate file, it defeats the purpose of having a custom module PostsContext.jsx created specifically as container for all things related to this PostsContext.

I would like for the warning to stop bugging me during development, but I don't want the HMR / Fast Refresh feature to break to the point of crashing as per https://github.com/jsx-eslint/eslint-plugin-react/issues/3176

The relevant parts in .eslintrc.cjs config file look like this:

plugins: ['react-refresh'],
rules: {
    'react-refresh/only-export-components': [
        'warn',
        { allowConstantExport: true }
    ]
}

Is there an explanation for what I'm missing here? eslint-plugin-react-refresh doesn't document turning on/off warnings or errors and does not give detailed explanations on proper usage. Can you please let me know how to handle this issue? Merci beaucoup!

ArnaudBarre commented 1 year ago

Yeah some docs are missing, but more from for React as a whole than Vite or this plugin. For now the only official doc is on the RN doc: https://reactnative.dev/docs/fast-refresh

Applying this to context providers means that you need to split the context creation and and the context provider in two files (that I put into one folder). This is a bit less nice but to be able to fast refresh providers is nice and it doesn't cost that much to split. And more and more I use zustand stores instead of React context.

About disabling Vite warning see this answer: https://github.com/vitejs/vite-plugin-react/issues/208#issuecomment-1682133347

lorand-horvath commented 1 year ago

@ArnaudBarre Thank you for your response! The best I could do was to split the file into index.js (exporting the context and the custom hook for 'using' it) and PostsProvider.jsx (exporting only the component) under the same directory PostsContext - this is good enough and fast refresh works as intended, vite doesn't complain.