I'm using React Strict Mode for a class project, and I have an issue where components will render multiple times, and nested components will render many, many times. I use routing, and this is how my components are structured so far:
Main component
Main screen component
Navbar component
Screen components (controlled through a React Router Switch)
So in this way, clicking through some screen components route you to others. However, components seem to render 2^x times, whatever x may be. I have a screen component, for example, that seemingly renders 16 times, as I have a console.log
statement that prints out 16 times.
I also query my backend in each component, using Apollo GraphQL, but in most of these renders it returns undefined, with is troublesome since I need to use that query data in functions and renders for those components. I structure my code like so:
const RegionViewer = (props) => {
const { currentRegion } = useParams();
const { data, refetch } = useQuery(GET_REGION, {variables: {regionId: currentRegion}});
const [addLandmark] = useMutation(mutations.ADD_LANDMARK);
const { data: subregions } = useQuery(GET_SUBREGIONS_BY_ID, {variables: {regionId: currentRegion}})
const { data: landmarks} = useQuery(GET_LANDMARKS, {variables: {region_id: currentRegion}});
const [input, setInput] = useState("");
const [target, setTarget] = useState({});
console.log(landmarks);
console.log(data);
console.log(subregions);
if (data && subregions && landmarks) {
const region = data.getRegion;
const numSubregions = subregions.getSubregionsById.length;
const updateInput = async (e) => {
const value = e.target.value;
setTarget(e.target);
await setInput(value);
}
const createLandmark = async () => {
console.log(region.landmarks);
if (input == "") {
alert("Please enter a landmark.");
}
else {
const {data} = await addLandmark({variables: {region_id: region._id, landmark: input}})
}
target.value = "";
setInput("");
await refetch();
}
return(<div>...</div>)
}
else return(<></>)
}
Because I query for multiple things, which return undefined multiple times (about 14 per each, and 2 defined returns), I just wrap everything in a conditional statement. I'm wondering if there is a better way around this, while still using strict mode. I tried using a lazyQuery that I invoke with useEffect, but that does not seem to help.