0

I have following react-component:

type Props = {
    country: string;
    electricityValues: number[];
    activeStep: number;
    setActiveStep: React.Dispatch<React.SetStateAction<number>>;
}

const EmissionsMemoized = (props: Props) => {
    const {country, electricityValues, activeStep, setActiveStep} = props;

    useEffect(() => {
        //make api call
    }, [electricityValues]);

    return (
        <>
            //...
        </>
    );
}

To avoid unnecessary rerender, I have memoized it like following:

export default function Emissions() {
    const {country, electricityValues, activeStep, setActiveStep} = useContext(AppContext);
    return useMemo(() => (<EmissionsMemoized country={country} electricityValues={electricityValues} activeStep={activeStep} setActiveStep={setActiveStep} />), []);
}

The component is being served in a Stepper-Component:

function getStepContent(step: number) {
    switch (step) {
//...
        case 2:
            return <Emissions />;
//...
    }
}

Unfortunately, useEffect() is getting triggered, making an API-call every time the Emissions-component is being returned by getStepContent(), regardless if state actually changed.

Any idea how to make useEffect() trigger only if value of electricityValues-array changes?

Is it because useContext() is returning a new reference every time?

Janez Kuhar
  • 3,705
  • 4
  • 22
  • 45
Hans
  • 1,162
  • 11
  • 18
  • Move the useContext within the EmissionsMemoized. I think it is happening because you are unmounting and mounting the component with the stepper code. – vijayst Aug 10 '21 at 12:45
  • Good idea. Moving useContext withing EmissionsMemoized had no effect though :-( Then I tried memoizing the Emissions-Component from within getStepContent() as in case 1: return useMemo(() => (), [country, electricityValues]); When stepping through, React complained about different number of hooks, so I had to memoize all the steps with the opposite effect and now it's always same component being returned by getStepContent. – Hans Aug 10 '21 at 13:06

0 Answers0