Be part of JetBrains PHPverse 2026 on June 9 – a free online event bringing PHP devs worldwide together.

kbeaud's avatar

HMR Invalidate: Could not Fast Refresh (React through Inertia.js)

I have tried searching a ton of threads, ChatGPT to debug. I am knocking my head against a wall trying to figure out why createContext() and useContext() are throwing this error, despite the fact I have set things up exactly the same in my other contexts and they were the exact same way. I have tried removing useToast() - still breaks. I have tried moving the Provider to top of the DOM tree - still breaks. As far as I know this is written exactly like my other contexts, and something about the context is screwing with things.

import React, { createContext, useContext, useState } from "react";
import { useToast } from "./ToastContext";

const FormErrorContext = createContext({
    formErrors: [],
    hasError: false,
    handleError: () => {},
});

export const useFormErrors = () => useContext(FormErrorContext);

const FormErrorProvider = ({ children }) => {
    const [formErrors, setFormErrors] = useState([]);
    const hasError = formErrors.length > 0 ? true : false;
    const { addToast } = useToast();

    const makeError = (alreadyAnError, id, needsToast, message) => {
        if (!alreadyAnError) {
            setFormErrors((prevErrors) => {
                const updatedErrors = [
                    ...prevErrors,
                    { input: id, errorMessage: message },
                ];

                return updatedErrors;
            });

            if (needsToast) {
                addToast({
                    type: "error",
                    message: message === "" ? "Invalid input" : message,
                    autoClose: 2500,
                });
            }
        }
    };

    const removeError = (alreadyAnError, id) => {
        if (alreadyAnError) {
            setFormErrors((prevErrors) => {
                const updatedErrors = [...prevErrors];
                const removedIndex = updatedErrors.findIndex(
                    (item) => item.input === id,
                );

                updatedErrors.splice(removedIndex, 1);

                return updatedErrors;
            });
        }
    };

    const handleError = (
        error = true,
        id,
        needsToast = false,
        message = "",
    ) => {
        const alreadyAnError = formErrors.find((item) => item.input === id)
            ? true
            : false;

        console.log("ran context");

        if (error) {
            makeError(alreadyAnError, id, needsToast, message);
        } else {
            removeError(alreadyAnError, id);
        }
    };

    return (
        <FormErrorContext.Provider
            value={{ formErrors, hasError, handleError }}
        >
            {children}
        </FormErrorContext.Provider>
    );
};

export default FormErrorProvider;

Apologies if there is an easy answer on this forum somewhere, I did try and do my due diligence, but I must be missing something here.

0 likes
1 reply
LaryAI's avatar
Level 58

It seems like you're encountering an issue with Hot Module Replacement (HMR) and React Fast Refresh when using createContext() and useContext() in your React application with Inertia.js. The error message you're seeing might be related to the way React Fast Refresh works with stateful logic and hooks.

Here's a potential solution to your problem:

  1. Ensure that your React components and hooks follow the rules of hooks, which include calling hooks at the top level and not inside loops, conditions, or nested functions.

  2. Make sure that your FormErrorProvider component is correctly wrapped around your application or the components that require access to the FormErrorContext.

  3. Check if there are any side effects in your context or components that might be causing issues with HMR. For example, ensure that the useToast hook is not causing side effects that might interfere with HMR.

  4. If you're using a custom server setup for HMR, ensure that it's configured correctly to support React Fast Refresh.

  5. If you're using a bundler like Webpack, make sure that you have the necessary plugins (like react-refresh-webpack-plugin) and configuration set up for React Fast Refresh.

  6. If none of the above solutions work, you can try to isolate the problem by creating a minimal reproduction of the issue. This means stripping down your application to the smallest version that still exhibits the problem and then gradually adding back features until you find the source of the issue.

Here's a simplified version of your FormErrorProvider that you can use as a starting point for debugging:

import React, { createContext, useContext, useState } from "react";

const FormErrorContext = createContext();

export const useFormErrors = () => useContext(FormErrorContext);

const FormErrorProvider = ({ children }) => {
    const [formErrors, setFormErrors] = useState([]);

    // Simplified handleError function for debugging purposes
    const handleError = (error, id) => {
        // Your error handling logic here
    };

    return (
        <FormErrorContext.Provider value={{ formErrors, handleError }}>
            {children}
        </FormErrorContext.Provider>
    );
};

export default FormErrorProvider;

Start with this simplified provider and see if HMR works correctly. If it does, gradually add back the other parts of your original FormErrorProvider until you find the part that causes the issue.

Remember that HMR and React Fast Refresh are meant to work with functional components and hooks in a way that preserves state while allowing you to see changes in real-time without a full page reload. If there's a complex stateful logic or side effects that don't align with the expectations of HMR, it might cause issues like the one you're experiencing.

Please or to participate in this conversation.