In the CurrentTime
example component earlier, the timestamp value should be generated only on the server (during server-side rendering) and somehow passed to the client so that the same value can be reused when the CurrentTime
component is mounted on the client side.
Try to think for a moment, how would you solve this problem? To make your life easier you can make use of the ExecutionEnvironment
utility that comes with the fbjs
package. It can be used like this:
import React from 'react'; import{ canUseDOM } from 'fbjs/lib/ExecutionEnvironment'; functionCurrentTime() { if (canUseDOM) { // TODO: Use the time generated on the server } else { time = Date.now(); } return<p>Current time (timestamp in ms): {time}</p>; } export default CurrentTime;
The fbjs
package is already used by React internally, so it should not increase the size of your application bundle. If you look at what's inside this ExecutionEnvironment
utility...