comunidad de Stack Overflow,
Estoy trabajando en un proyecto de Next 14 y me encontré con algunas advertencias relacionadas con las dependencias de mi hook y en un componente random. Estoy utilizando useEffect y useCallback, y recibo advertencias sobre dependencias que faltan:
./src/components/app/ScheduleSelector.tsx
87:6 Warning: React Hook useEffect has missing dependencies: 'selectDate' and 'serviceDate'. Either include them or remove the dependency array. If 'selectDate' changes too often, find the parent component that defines it and wrap that definition in useCallback. react-hooks/exhaustive-deps
./src/hooks/useAvailability.tsx
56:5 Warning: React Hook useCallback has a missing dependency: 'endDate'. Either include it or remove the dependency array. react-hooks/exhaustive-deps
61:6 Warning: React Hook useEffect has a missing dependency: 'loadSlots'. Either include it or remove the dependency array. react-hooks/exhaustive-deps
67:6 Warning: React Hook useEffect has a missing dependency: 'loadAvailability'. Either include it or remove the dependency array. react-hooks/exhaustive-deps
Mi problema es que, si agrego estas constantes como dependencias, cambia el comportamiento del componente. Necesito que el efecto se ejecute solo cuando el componente se monta y no en cada actualización.
"use client";
import { useEffect, useState, useCallback, use } from "react";
import { AvailableSlot } from "@/services/AppointmentsService";
import * as ServerAppointmentService from "@/services/ServerAppointmentService";
import { SlotCheck } from "@/services/SlotsService";
export function useAvailability({
date,
service,
endDate,
}: {
date: Date | undefined;
service: { id: string; staffId: string | undefined };
endDate?: Date;
}) {
const [availability, setAvailability] = useState<AvailableSlot[]>([]);
const [slots, setSlots] = useState<SlotCheck[]>([]);
const [loading, setLoading] = useState(false);
const loadAvailability = useCallback(
async (date: Date) => {
setLoading(true);
try {
const data = await ServerAppointmentService.getAvailability({
date,
service,
});
setAvailability(data);
} catch (error) {
console.error("Error loading availability", error);
} finally {
setLoading(false);
}
},
[service],
);
const loadSlots = useCallback(
async (date: Date) => {
setLoading(true);
try {
const data = await ServerAppointmentService.getSlotsAvailability({
startDate: date.toISOString(),
endDate: endDate?.toISOString(),
staffId: service.staffId,
serviceId: service.id,
});
setSlots(data);
} catch (error) {
console.error("Error loading availability", error);
} finally {
setLoading(false);
}
},
[service],
);
useEffect(() => {
loadSlots(new Date());
}, [date]);
useEffect(() => {
if (date) {
loadAvailability(date);
}
}, [date]);
return {
availability,
loading,
loadAvailability,
slots,
};
}
¿Alguna sugerencia aparte de deshabilitar el lint?
Gracias de antemano por cualquier información.
Saludos comunidad.