
createContextとuseContext使用で警告が出る
Reactで以下のように同一ファイル内でcreateContextとuseContextを使用すると、ESLintの「react-refresh/only-export-components」ルールが有効だと、以下の警告が出ます。
Fast refresh only works when a file only exports components. Use a new file to share constants or functions between components.
CountContext.tsx
import { createContext, useContext } from 'react'
import { State, Action } from './types'
export const CountContext = createContext<{
state: State
dispatch: React.Dispatch<Action>
} | undefined>(undefined)
// react-refresh/only-export-components の警告が出る
export function useCount() {
const context = useContext(CountContext)
if (!context) {
throw new Error('useCount must be used within a CountProvider')
}
return context
}
この警告は、useCount()を別ファイルに保存してexportすれば解決できます。
useCount.tsx
import { useContext } from 'react'
import { CountContext } from './CountContext'
export function useCount() {
const context = useContext(CountContext)
if (!context) {
throw new Error('useCount must be used within a CountProvider')
}
return context
}
react-refresh/only-export-components のESLintルールは以下のような関数とコンポーネントのどうファイル内でのexportで発生するイメージなので、createContextとuseContextでも発生するというのは慣れていないと気づきにくいかもしれません。
TSX
export const foo = () => {};
export const Bar = () => <></>;
createContextとuseContext使用で警告が出るサンプル