I'm building a website with React and recently switched to using server-side rendering (SSR) for improved performance. One issue I ran into after this change is that when I format a time on the page (I'm using Moment.js) it renders incorrectly using the server's time zone.
How can I format the time using the client's time zone? Do I need to leave the time off on the server response and have the client render that afterwards?
This means that, generally speaking, SSR will outperform CSR. SSR apps break JavaScript and CSS into chunks, optimize assets, and render pages on the server before serving to the client browser, resulting in a faster initial load time.
Server-side rendering allows developers to pre-populate a web page with custom user data directly on the server. It is generally faster to make all the requests within a server than making extra browser-to-server round-trips for them. This is what developers used to do before client-side rendering.
Server-side rendering improves site speed and results in better Core Web Vitals scores. However, sometimes it can be difficult to implement and might also increase First Input Delay.
Client-Side Rendering By default, your React app will be client-side rendered. This means basically, all of the source code will live in JavaScript files referenced in a single HTML file that initializes your app.
Do I need to leave the time off on the server response and have the client render that afterwards?
Unfortunately yes.
You can build a utility component to make this less tedious.
Class component:
// utility
import React, { Component } from 'react';
// Class component
export default class ClientRender extends Component {
state = { isMounted: false };
componentDidMount () {
this.setState({ isMounted: true });
}
render () {
const { children } = this.props;
const { isMounted } = this.state;
return isMounted ? children : null;
}
}
// Function component
export default function ClientRender({ children }) {
const [isMounted, setIsMounted] = React.useState(false);
React.useEffect(() => {
setIsMounted(true);
}, []);
return isMounted ? children : null;
}
// in your app
import React from 'react';
import moment from 'moment';
import ClientRender from './path/to/client-render';
export default function MyComponent (props) {
return (
<div>
<ClientRender>{moment(props.timeUTC * 1000).format('LLL')}</ClientRender>
</div>
);
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With