Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Ensure useFromNow does not trigger any re-render (impl dom level update) #905

Open
wants to merge 1 commit into
base: main
Choose a base branch
from

Conversation

garronej
Copy link
Contributor

No description provided.

@garronej garronej requested a review from ddecrulle December 19, 2024 12:58
@garronej
Copy link
Contributor Author

We don't have to merge it if you don't want to but it's intresting enough

Comment on lines +16 to +48
export function useFromNow(params: { dateTime: number | undefined }) {
const { dateTime } = params;

const id = useId();

const fromNowText = useMemo(() => <span id={id}></span>, [id]);

const updateNode = useConstCallback(() => {
if (dateTime === undefined) {
return;
}

const el = document.getElementById(id);

if (el === null) {
return;
}

el.innerHTML = fromNow({ dateTime });
});

useEffect(() => {
updateNode();
}, [dateTime, id]);

useEffect(() => {
const timer = setInterval(updateNode, 1000);

return () => clearInterval(timer);
}, []);

return { fromNowText };
}
Copy link
Contributor

@ddecrulle ddecrulle Dec 20, 2024

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

This is an interesting implementation. In my opinion, it's much more convenient that the hook returned a string instead of a ReactNode. Additionally, there is a type issue: fromNowText is currently typed as any. While this implementation is more complex than the previous one and has some benefits, I don’t believe they are sufficient to justify merging it.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

Successfully merging this pull request may close these issues.

2 participants