Skip to content

Formatting relative times with useNow should sync "instantly" client side when component re-render #1404

Answered by amannn
theoludwig asked this question in Q&A
Discussion options

You must be logged in to vote

now refers to a global value that is shared across your whole application. updateInterval can help to sync it periodically for a given call site, but according to the rules of React, the value is not updated just by a component re-rendering—a React component should always be ready to render.

Instead, for your case you can make this more explicit, e.g. creating a value now based on the initial global value:

const [now, setNow] = useState(useNow());

… and later updating it for every interaction that you find "worthy" of updating the time:

      <button
        onClick={() => {
          setNow(new Date())
          // ...

I'll move this to a discussion since this is a usage question.

Replies: 1 comment 2 replies

Comment options

You must be logged in to vote
2 replies
@theoludwig
Comment options

@ChristianIvicevic
Comment options

Answer selected by theoludwig
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Category
Q&A
Labels
bug Something isn't working unconfirmed Needs triage.
3 participants
Converted from issue

This discussion was converted from issue #1402 on October 07, 2024 16:00.