Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to format time in React SSR rendered page using client time zone?

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?

like image 535
Liron Yahdav Avatar asked Jun 15 '18 23:06

Liron Yahdav


People also ask

Is SSR faster than CSR?

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.

Why is server-side rendering faster?

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.

Does server-side rendering improve performance?

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.

Is React client-side rendering or server-side rendering?

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.


1 Answers

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>
  );
}
like image 190
Mo Kouli Avatar answered Oct 07 '22 09:10

Mo Kouli