I have a custom useEffect hook to get current time every minute.
const useDateStatus = () => {
const [date, setDate] = useState(new Date());
useEffect(() => {
const interval = setInterval(() => {
setDate(() => new Date());
}, 60000);
return () => clearInterval(interval);
}, []);
return date;
};
I need to a common component that when the date fall in the given time range, the component renders null, otherwise it will display the date
.
const DateAlert = ({timeRanges, children}) => {
const date = useDateStatus();
if (!inRanges(date, timeRanges)) {
return null;
}
return (
<Alert>
<p>{date}</p>
{children}
</Alert>
);
};
I also need another common component that don't need the date object.
const Display = ({timeRanges, children}) => {
const date = useDateStatus();
if (!inRanges(date, timeRanges)) {
return null;
}
return children;
};
Should I create a context to contain the date
in order to pass the date
props and then make the DateAlert
to use the context?
const context = React.createContext(new Date());
const DateContext = ({children}) => {
const date = useDateStatus(new Date);
return (
<context.Provider value={date}>
{children}
</context.Provider>
);
}
I need to get the date
state, from How to pass props to {this.props.children}, I think it's good to use context to pass the date
as props to children.
What's the difference between using the context to get the date
or directly call useDateStatus()
to get the date?
Or is there a better way to reduce the redundancy between DateAlert
and Display
?