Next.js - Fast Refresh



Fast Refresh

Fast Refresh is a React feature integrated to Next.js that allows you to update your code and see the changes in real-time without having to refresh the page. This is a great feature for developers who are working on large applications or who want to see the changes they make in their code immediately.

How Fast Refresh works?

  • If you edit a file that only exports React component(s), Next.js will update the code only for that file, and re-render your component.
  • If you edit a file with exports that aren't React components, Next.js will re-run both that file, and the other files importing it. So if both Button.js and Modal.js import theme.js, editing theme.js will update both components.
  • Finally, if you edit a file that's imported by files outside of the React tree, Fast Refresh will fall back to doing a full reload. You might have a file which renders a React component but also exports a value that is imported by a non-React component. In this case, Fast Refresh will re-run the entire application.

Features of Fast Refresh

  • Real-Time Updates: Changes to components or styles are applied immediately, maintaining component state and avoiding full page reloads.
  • Automatic Activation: Fast Refresh is enabled by default in Next.js, no extra configuration is needed.
  • State Preservation: Fast Refresh retains component state across updates, improving development workflow and reducing the need for manual refreshes.

Example of Fast Refresh

From the Next.js 9 onwards, Fast Refresh is enabled by default. So if you make any changes to your code, you will see the changes immediately. Here we defined a simple Next.js home page to demonstrate the Fast Refresh feature.

// File: app/page.tsx

export default function Home() {
    return (
        <div>
            <h1>Home Page</h1>
            <p>This is the home page.</p>
        </div>
    );
}

Output

Next.js Fast Refresh

Disable Fast Refresh

In Next.js, Fast Refresh is enabled by default in development mode. If you need to disable Fast Refresh, you can do so by modifying the Next.js configuration. Open your next.config.js file (create one if it doesn't exist) and add the following line:

// File: next.config.js

module.exports = {
    experimental: {
      reactRefresh: false,
    },
  };
Advertisements