Fast Refresh Internals
Relevant source files
The following files were used as context for generating this wiki page:
- packages/react-refresh/src/ReactFreshBabelPlugin.js
- packages/react-refresh/src/ReactFreshRuntime.js
- packages/react-reconciler/src/ReactFiberHotReloading.js
- packages/react-refresh/src/tests/ReactFreshIntegration-test.js
- packages/react-refresh/src/tests/ReactFresh-test.js
- packages/react-devtools-shared/src/tests/FastRefreshDevToolsIntegration-test.js
Fast Refresh is a React feature that provides instant feedback for edits made to React components. It is designed to preserve component state between edits, allowing for a smoother and faster development experience. This is achieved through a combination of a Babel plugin, a runtime script, and integration with the React reconciler.
The system works by instrumenting component modules at build time to register them with a special runtime. When a module is updated, the runtime can swap the implementation of the component on the fly. It intelligently decides whether to simply re-render a component with its existing state or to perform a full remount based on the nature of the code changes.
Architecture Overview
The Fast Refresh mechanism involves three main parts:
- Babel Plugin (
react-refresh/babel): Transforms component code during the build process to inject hooks that communicate with the Fast Refresh runtime. - Runtime (
react-refresh/runtime): A small script that runs in the browser, manages component "families", and orchestrates the refresh process. - Reconciler Integration (
react-reconciler): The React reconciler provides the low-level API (scheduleRefresh) to schedule an update for a specific fiber root without losing state.
This diagram illustrates the high-level data flow when a developer saves a file.
Babel Transformation
The react-refresh/babel plugin is responsible for instrumenting the code. It identifies React components and injects calls to two global functions that the Fast Refresh runtime exposes: $RefreshReg$ and $RefreshSig$.
$RefreshReg$(type, id): This function is used to register a component type with the runtime. Theidis a unique identifier for the component within its module.$RefreshSig$(): This function returns another function that is used to create a "signature" for a component. This signature is based on the hooks used within the component (e.g.,useState,useEffect). The signature is crucial for determining if a component's state can be preserved across edits.
The following test utility demonstrates how the Babel transform is configured and executed.
Sources: packages/react-refresh/src/tests/ReactFreshIntegration-test.js:63-76
function executeJavaScript(source, compileDestructuring) {
const compiled = babel.transform(source, {
babelrc: false,
presets: ['@babel/react'],
plugins: [
[freshPlugin, {skipEnvCheck: true}],
'@babel/plugin-transform-modules-commonjs',
compileDestructuring && '@babel/plugin-transform-destructuring',
].filter(Boolean),
}).code;
return executeCompiled(compiled);
}
The test environment simulates the bundler's behavior by defining $RefreshReg$ and $RefreshSig$ functions that call the runtime.
Sources: packages/react-refresh/src/tests/ReactFreshIntegration-test.js:89-96
function $RefreshReg$(type, id) {
ReactFreshRuntime.register(type, id);
}
function $RefreshSig$() {
return ReactFreshRuntime.createSignatureFunctionForTransform();
}
Fast Refresh Runtime
The react-refresh/runtime module is the core of the Fast Refresh feature. It exposes the API that allows the Babel plugin and the application's module system to coordinate updates.
Key Functions
| Function | Description |
|---|---|
register(type, id) | Registers a component type with a given id. This allows the runtime to track different versions of the same component. |
setSignature(type, key, forceReset, getCustomHooks) | Associates a component type with a signature key. The signature is used to detect changes in hooks that would require a state reset. forceReset can be used to always remount. |
performReactRefresh() | This is the main function called by the developer's application or framework to trigger a refresh. It compares registered component types and schedules updates for any that have changed. |
getFamilyByType(type) | Retrieves the "family" for a given component type. A family represents all versions of a single component. This is used to check if a component's fundamental type has changed (e.g., from a function to a class). |
Sources: packages/react-refresh/src/ReactFreshRuntime.js, packages/react-refresh/src/tests/ReactFresh-test.js
The Refresh Process
The refresh process is orchestrated by performReactRefresh. This diagram shows the sequence of events when a refresh is triggered.
This diagram shows the sequence of operations when performReactRefresh is called. It checks for updated component families and uses the reconciler to schedule the update.
Sources: packages/react-refresh/src/ReactFreshRuntime.js, packages/react-reconciler/src/ReactFiberHotReloading.js
Reconciler Integration
Fast Refresh integrates with React's reconciler via the react-reconciler package. The key function provided by the reconciler for hot reloading is scheduleRefresh.
scheduleRefresh(root, update): This function is called by the Fast Refresh runtime. It takes a fiberrootand anupdateobject containing the set of updated component "families". The reconciler then walks the fiber tree and forces an update on any instances that match the updated families, preserving their state if possible.
The hot reloading logic within the reconciler is primarily located in ReactFiberHotReloading.js. This file contains the implementation for scheduleRefresh and the logic for finding and updating fibers corresponding to the new component types.
Sources: packages/react-reconciler/src/ReactFiberHotReloading.js
State Preservation and Remounting
Fast Refresh aims to preserve component state whenever possible. However, certain changes require a full remount, which resets the state.
Conditions for Preserving State
- The component type remains compatible (e.g., stays a function component).
- The order and signature of hooks (
useState,useEffect, etc.) do not change. The signature is a string generated by the Babel plugin based on the hooks used.
Conditions for a Full Remount
A component will be remounted (losing its state) if:
- It changes from a function component to a class component, or vice-versa.
- It is wrapped in a new Higher-Order Component (HOC) like
memoorforwardRef. - The signature of its hooks changes (e.g., adding, removing, or reordering hooks).
- The developer explicitly opts-in to a remount by adding a
/* @refresh reset */comment in the source file.
The integration tests provide many examples of these scenarios. For instance, changing the initial value of a useState call is detected and triggers a remount to avoid inconsistent state.
Sources: packages/react-refresh/src/tests/ReactFreshIntegration-test.js:1012-1041
it('resets state when useState initial state is edited', async () => {
if (__DEV__) {
await render(`
const {useState} = React;
export default function App() {
const [foo, setFoo] = useState(1);
return <h1>A{foo}</h1>;
}
`);
let el = container.firstChild;
expect(el.textContent).toBe('A1');
await patch(`
const {useState} = React;
export default function App() {
const [foo, setFoo] = useState(1);
return <h1>B{foo}</h1>;
}
`);
// Same initial state, so it's preserved.
expect(container.firstChild).toBe(el);
expect(el.textContent).toBe('B1');
await patch(`
const {useState} = React;
export default function App() {
const [foo, setFoo] = useState(2);
return <h1>C{foo}</h1>;
}
`);
// Different initial state, so state is reset.
expect(container.firstChild).not.toBe(el);
el = container.firstChild;
expect(el.textContent).toBe('C2');
}
});
DevTools Integration
Fast Refresh is also integrated with React DevTools. When a component is updated via Fast Refresh, the DevTools UI reflects the changes without losing the component's position in the tree or its inspection state, unless a full remount was necessary. This ensures a consistent debugging experience.
Tests in FastRefreshDevToolsIntegration-test.js verify that the DevTools store remains consistent across patches, and that component state is preserved or reset as expected.
Sources: packages/react-devtools-shared/src/tests/FastRefreshDevToolsIntegration-test.js:124-150
it('should not break the DevTools store', () => {
render(`
function Parent() {
return <Child key="A" />;
};
function Child() {
return <div />;
};
export default Parent;
`);
expect(store).toMatchInlineSnapshot(`
[root]
▾ <Parent>
<Child key="A">
`);
let element = getContainer().firstChild;
expect(getContainer().firstChild).not.toBe(null);
patch(`
function Parent() {
return <Child key="A" />;
};
function Child() {
return <div />;
};
export default Parent;
`);
expect(store).toMatchInlineSnapshot(`
[root]
▾ <Parent>
<Child key="A">
`);
// State is preserved; this verifies that Fast Refresh is wired up.
expect(getContainer().firstChild).toBe(element);
element = getContainer().firstChild;
});
Summary
Fast Refresh is a sophisticated system that significantly improves the React development workflow. By combining build-time code transformation with a dedicated runtime and deep integration into the React reconciler, it can apply hot updates to components while preserving their state. This allows developers to see the results of their changes almost instantly, without losing the context of their work. The system is carefully designed to be resilient, handling a wide variety of component types, hooks, and edge cases to decide when to perform a simple re-render versus a full remount.