Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Bug: Rendered more hooks than during the previous render. #370

Open
betula opened this issue Jun 7, 2023 · 2 comments
Open

Bug: Rendered more hooks than during the previous render. #370

betula opened this issue Jun 7, 2023 · 2 comments
Labels

Comments

@betula
Copy link

betula commented Jun 7, 2023

I attached archive with small project on Vite that reproduced error:

react-rendered-more-hooks.zip

Screen.Recording.2023-06-07.at.12.04.09.mov
@LaiArturs
Copy link

I am not sure if it is related but might help someone looking for a solution to a similar problem.

I also had a "Rendered more hooks than during the previous render" error. This error showed in Chrome but not in Firefox. Running code in Firefox turend out I had another valid issue with my code: "Each child in a list should have a unique "key" prop".

As soon as I solved this error, "Rendered more hooks than during the previous render" error was also solved.

@Joaco2603
Copy link

Tuve el mismo problema, lo que fue mi solución fue pasar 2 if que tenia arriba de los hooks para abajo, esto porque react espera que la cantidad de hooks declarados siempre sea la misma por lo tanto, si hay un codigo bloqueante, o bucle no va a funcionar, mi código primero estuvo así .

Codigo erróneo.
`const [showModal, setShowModal] = React.useState(false);

//Este Loading tiene que estar abajo del compoente
const { isLoading, error, data } = useCreateQuery({
queryKey: "rol",
url: "/rol",
});

// Retorna el loader o el error antes de los hooks adicionales
if (isLoading) return ;
if (error) return

Error: {error.message}

;

const { register, handleSubmit } = useForm();
const newEmployee = useCreateEmployeeMutation();

const onSubmit = (data: any) => {
newEmployee.mutateAsync(data);
};
`

Finalmente el código corregido es este.

Código corregido.
`
const [showModal, setShowModal] = React.useState(false);

const { isLoading, error, data } = useCreateQuery({
queryKey: "rol",
url: "/rol",
});

// Estos hooks ahora solo se ejecutan una vez que isLoading es falso y no hay error
const { register, handleSubmit } = useForm();
const newEmployee = useCreateEmployeeMutation();

const onSubmit = (data: any) => {
newEmployee.mutateAsync(data);
};

if (isLoading) return ;
if (error) return

Error: {error.message}

;
`

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
Projects
None yet
Development

No branches or pull requests

4 participants