Closed dchenk closed 2 years ago
@dchenk Hello! Thanks for raising this issue. Answering your questions:
Is there a real reason the initial state object is first serialized to a JSON string and then that JSON string is itself stringified again?
As far as I understand, parsing JSON is faster for the browser than parsing JavaScript. Therefore, it's interesting to have the state object as a string where we apply JSON.parse
later instead of having a literal JS object (which has more complex grammar, read more here if you are interested).
However, what you say about the escape characters is true. I intended to address this at some point but forgot about it.
If not, would you accept a PR that removes the needless extra JSON.stringify?
Considering the previous answer, we can probably agree that instead of removing it completely, we could do this:
return "'" + JSON.stringify(state || {}).replace(...) + "'"
I think this effectively removes the extra escaping characters while keeping it as a string. Thoughts? If that makes sense, feel free to submit a PR!
I noticed that the
__INITIAL_STATE__
object that was being inserted into the HTML had lots of escaped double quote characters (i.e.,\"
), and it was because the entire initial state object was itself a string. Apparently the initial state is put throughJSON.stringify
twice before unsafe characters are escaped! That seemed odd and unnecessary to me, so in my project I changed that part of the code inserializeState
to JSON.stringify only once and indeserializeState
to simply returnstate || {}
without extra parsing. It turns out this works just fine—all unsafe characters are properly escaped, and there is far less overhead in transmitting/parsing the initial state object this way.A couple questions: