"Too many re-renders" error while passing data from React Context

Viewed 29

Context.js

    i18n
    .use(initReactI18next) // passes i18n down to react-i18next
    .init({
      resources: {
        en: { translation: translationsEn },
        bn: { translation: translationsBn },
      },
      lng: "bn",
      fallbackLng: "bn",
      interpolation: { escapeValue: false },
    });
  

  const { t } = useTranslation();
  
 const onChange = (event) => {
    i18n.changeLanguage(event.target.value);
    setCount((previousCount) => previousCount + 1);
  }; 

Component.js

<Select
defaultValue={"en"}
variant="outlined"
displayEmpty
name="language"
notched={false}
size="small"
onChange={onChange}
sx={{
color: "other.white",
border: "2px",
"&:hover": {
border: "2px",
},
}}
>
<MenuItem value="en">English</MenuItem>
<MenuItem value="bn">বাংলা</MenuItem>
</Select>

This is the code of my context fil, where I have written the i18n codes. I want to access the translation from the context in my other components. Context is working properly,which I have checked using console, data are passing properly. But the context page is rendering too many times, because it shows the error "it is in an infinite loop". How can I resolve this issue? How can I stop re- rendering my context file.

1 Answers

I think the issue is you called onChange directly, not using a callback function like this

<Select
defaultValue={"en"}
variant="outlined"
displayEmpty
name="language"
notched={false}
size="small"
onChange={(e)=>onChange(e)}
sx={{
color: "other.white",
border: "2px",
"&:hover": {
border: "2px",
},
}}
>
<MenuItem value="en">English</MenuItem>
<MenuItem value="bn">বাংলা</MenuItem>
</Select>
Related