react-rails icon indicating copy to clipboard operation
react-rails copied to clipboard

Non-deterministic `to_json` of props object leads to server-client mismatches when using SSR

Open hibachrach opened this issue 5 years ago • 1 comments

Steps to reproduce

Render a react component within a view file (e.g. ERB/Haml) with the components props being a non-String object that responds to to_json with results that are impure or non-nondeterministic (e.g. Random.rand, SecureRandom.uuid, Time.now.to_i, etc.)

Expected behavior

The server-side rendered body of the component are generated using the props serialized into the wrapping tag so client-side React does not have to make a DOM update

Actual behavior

The props are generated (i.e. to_json) twice: once for the SSR of the component and once for the rest of the view and the wrapping tag.

System configuration

Sprockets or Webpacker version: 4.0.7 React-Rails version: 2.6.0 React_UJS version: 2.6.0 Rails version: 6.0.3.4 Ruby version: 2.5.8


I think this is a very niche case that only came up b/c I was doing some ad-hoc testing so feel free to close this as a "wontfix"

Here are the two places it looks like it's being called:

https://github.com/reactjs/react-rails/blob/43b97a59c370ed07e01f568c6458dd8f72eab1f7/lib/react/rails/component_mount.rb#L45 https://github.com/reactjs/react-rails/blob/43b97a59c370ed07e01f568c6458dd8f72eab1f7/lib/react/server_rendering/bundle_renderer.rb#L92

hibachrach avatar Dec 02 '20 18:12 hibachrach

Just wanted to note the double to_json also has some performance implications if the to_json call is a little expensive (e.g., involves an active record query). We just make sure we call to_json (turning it into a string) on our props object before passing it to react_component but it would be nice if clients of react-rails didn't have to worry about it.

erikt9 avatar Jan 29 '21 19:01 erikt9

@hibachrach Were you able to resolve this issue? Closing this for now. Feel free to reopen it.

alkesh26 avatar Nov 16 '22 07:11 alkesh26

I wasn't but it only came up when debugging.

hibachrach avatar Nov 17 '22 00:11 hibachrach