1

Here is my code:

App.js

import React from "react";
import Child from "./Child";
import { VariableCreator } from "./Context";

const App = () => {
  return (
    <VariableCreator>
      <Child />
    </VariableCreator>
  );
};

export default App;

Child.js

import React, { useState } from "react";
import { useVariable } from "./Context";

const Child = () => {
  const msg = useVariable();

  return <div>your message is: {msg}</div>;
};

export default Child;

Context.js

import React, { useState, useContext } from "react";

//create context variable
const Variable = React.createContext();

//creator
export function VariableCreator({ children }) {
  const boolean = true;
  const [msg, setMsg] = useState("");

  if (boolean === true) {
    setMsg("Message: True");
  } else {
    setMsg("Message: False");
  }

  return <Variable.Provider value={msg}>{children}</Variable.Provider>;
}

//get
export function useVariable() {
  return useContext(Variable);
}

I am practicing useContext hook.

What I am trying to do is to set a boolean value and treat it as a context. Then I try to access the boolean value and then assign it to a variable "msg" using useState hook. Finally I want to log the "msg" out in Child.js.

But I got the below error:

Uncaught Error: Too many re-renders. React limits the number of renders to prevent an infinite loop.

My code doesn't involve any value change at all. Just a simple display program render ONCE only. So my question is: why the above program has infinite loop?

Thank you.

  • Add the `if (boolean)` check inside an useEffect with empty dependency array. This way this if check will run only once – Inder May 01 '22 at 13:45
  • I think the problem is because of const boolean = true; Keep it as part of state too, or take it our of component. What is happening in your code: the component renders, inside there is a variable, it checks, if it is true, useState is called, component rerenders, that variable is created again, again checks, again sets and you get an infinite loop. Keep loading as a part of state too and I think it will work as it supposed to work. – Tigran Petrosyan May 01 '22 at 13:51
  • @Inder Thank you for your attention. My friend also suggested a similar solution as yours. But may I ask why my code has infinite loop? – wongwong3000 May 01 '22 at 13:51
  • @wongwong3000 Checkout the comment by Tigran Petrosyan. He has explained it beautifully. Thats the exact reason why your code is causing infinite rerenders. Its upto you if you want to maintain a separate state for boolean, if not then use UseEffect hook with empty dependency array – Inder May 01 '22 at 13:53
  • Thank you @Tigran Petrosyan ! I know the reason now! your explanation is SUPER clear! – wongwong3000 May 01 '22 at 14:46
  • @Inder Thank you for your follow up. Finally I find out why :) – wongwong3000 May 01 '22 at 14:48

0 Answers0