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.