Created
July 25, 2019 12:53
-
-
Save hoodwink73/3249c2049c743e567a4072c69ac10ec6 to your computer and use it in GitHub Desktop.
Suppose you have different parts of the app which needs to change(re-render) after a certain time, say like timers — this is how you would achieve it with React hooks
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
import React, { useState, useEffect, useContext, createContext } from "react"; | |
import moment from "moment"; | |
const BeatContext = createContext(); | |
export function BeatProvider({ beatEveryInMs, children }) { | |
const [lastUpdated, update] = useState(moment()); | |
const secondsInNow = moment().seconds(); | |
// this tries to ensure we trigger the update when the minute changes | |
// in real world | |
// NOTE: If you want updates to happen after duration less than a minute | |
// this code will not work | |
const scheduleTime = (beatEveryInMs / 1000 - secondsInNow) * 1000; | |
useEffect(() => { | |
const unsubscribeID = setTimeout(() => { | |
update(moment()); | |
}, scheduleTime); | |
return () => clearTimeout(unsubscribeID); | |
}); | |
return ( | |
<BeatContext.Provider value={lastUpdated}>{children}</BeatContext.Provider> | |
); | |
} | |
export function useBeat() { | |
const lastUpdated = useContext(BeatContext); | |
return lastUpdated; | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment