Sorry I'm new to React, and so I faced a problem where I have my Context which provides the Time to other components. When I use it only with the component where I display my clock everything is fine. The problem occurs in another component, where I want to display message depending on the time of the day. Too many re-renders. React limits the number of renders to prevent an infinite loop.
My Context Component
import React, { createContext, useState, useEffect } from "react";
import moment from "moment";
export const GreetingContext = createContext();
const getTime = () => {
return moment();
};
const GreetingContextProvider = (props) => {
const [currentTime, setCurrentTime] = useState(getTime);
const setTime = () => {
setInterval(() => {
setCurrentTime(getTime);
}, 1000);
return () => {
clearInterval(setTime);
};
};
useEffect(setTime, []);
return (
<GreetingContext.Provider value={currentTime}>
{props.children}
</GreetingContext.Provider>
);
};
export default GreetingContextProvider;
And my Message Component
import React, { useState, useContext} from "react";
import { useLocalStorage } from "../custome_hooks/useLocalStorage";
import { GreetingContext } from "../contexts/GreetingContext";
const Greeting = () => {
const time = useContext(GreetingContext);
const timeInHours = time.hours();
const [greeting, setGreeting] = useState("ooo");
const [name, setName] = useLocalStorage("name", "Your name");
// Setting the greeting depending on the time of the day
switch (true) {
case timeInHours > 0 && timeInHours < 5:
setGreeting("Good night");
break;
case timeInHours > 5 && timeInHours < 12:
setGreeting("Good morning");
break;
case timeInHours > 12 && timeInHours < 17:
setGreeting("Good day");
break;
case timeInHours > 17 && timeInHours < 24:
setGreeting("Good evening");
break;
default:
setGreeting("");
}
// Getting the name of the user
let handleChange = (e) => {
setName(e.target.value);
};
return (
<div className="greeting_container">
<h4>{greeting}</h4>
<input
type="text"
size={name.length + 1}
value={name}
onChange={handleChange}
/>
</div>
);
};
export default Greeting;
Thanks