Skip to content

Monkeypatch Math.random(), new Date() and Date.now() during render() in dev #1077

Closed

Description

@petehunt

Was talking with Adam Wolff today about rxjs and there are a ton of common bugs with these functions. You're gonna have a bad time if you use these in React render() methods too -- if we monkeypatched these to warn in __DEV__ we could prevent some bugs. @jordwalke seemed to like the idea too.

Activity

  1. vjeux commented on Feb 14, 2014

    @vjeux
    Contributor

    Can you give an example of such bug?

  2. zpao commented on Feb 14, 2014

    @zpao
    Contributor

    I will respectfully say "meh" and that I generally don't agree with overriding builtins. Would love to hear more about the bugs encountered.

  3. petehunt commented on Feb 14, 2014

    @petehunt
    ContributorAuthor

    Anytime you call anything in render() that uses these you may break server rendering or make some interactions behave strangely. This is a bug we had at Instagram -- you should not read from the rng or clock in a reactive system since your code may be rerun at any time.

  4. syranide commented on Feb 14, 2014

    @syranide
    Contributor

    @petehunt But how would you then deal with information relative to current time? I.e, "blog post is X hours old", "person is X years and Y days old", "message received X seconds ago".

  5. chenglou commented on Feb 14, 2014

    @chenglou
    Contributor

    ^ Agreed. I think these are far more common.
    (You guys want at least a tip entry? lol)

  6. steveluscher commented on Jul 15, 2014

    @steveluscher
    Contributor

    @syranide Whenever I have the need to display information relative to the current time, I commonly also want to keep that current with the passage of time. Hence, I'm likely to store an “age” value in the component state, and keep it up to date with a timer, rather than to calculate the age at render-time.

    More generally, I think we want to wedge people into a place where their render methods depend on component state and props as much as possible, and component-external/global state as little as possible (preferably not at all). Thoughts?

  7. syranide commented on Jul 15, 2014

    @syranide
    Contributor

    @steveluscher That sounds kind of fragile to me, I think time is ubiquitous enough that Date.now() should be exported by React as React.now(). So that when any rendering inside React takes place, time is frozen and all subsequent calls to React.now() returns that same time.

    For React.renderComponentToString the frozen time would also be added to the root element next to the checksum, which would be used for the initial rendering on the client when reusing the DOM.

    Aside from just fixing mismatches between client and server rendering, it would also prevent edge-case inconsistencies in rendering. Two identical timer components can currently show slightly varying times, or say an item could show as expired in one place and not expired in another if the timing is just right. This would prevent that entirely.

    @petehunt Any spontaneous reaction?

  8. steveluscher commented on Jul 16, 2014

    @steveluscher
    Contributor

    @syranide I'm intrigued by the idea of a frozen render-pass timestamp (your React.now() idea). Let's explore that some more! Might certainly help catch some of the edge-cases you mentioned, and be useful to sync up client/server rendering.

    The specific example about “age” aside, the general point I wanted to make was that depending on external state (like time) in render methods means that those renders won't behave like pure functions. Pure renders are a bit easier to reason about, optimize, and test.

    And with respect to storing age/displayAge in state; I like being able to surgically update the display age using a timer. It lets me vary the update frequency (commented X minutes ago => set a timer to go off when the result will be X+1 minutes) and it beats having to call forceUpdate() on the whole component just to calculate a fresh relative timestamp.

  9. petehunt commented on Jul 16, 2014

    @petehunt
    ContributorAuthor

    This sounds like it'll be super confusing when one component uses React.now() and another one messes up and uses Date.now().

    Would prefer if we monkeypatched Date.now(), Math.random() and friends to log a friendly warning if called while in a reconcile

  10. syranide commented on Jul 16, 2014

    @syranide
    Contributor

    @petehunt I see your point and unless I'm mistaken it would only be confusing/broken for the component that uses Date.now().

    I'm not sure if I understand your intention about monkey-patching Date.now() and Math.random() to warn the user, I agree with that part. But isn't time ubiquitous enough that we should provide a utility for it, rather than have everyone invent their own? Especially since, as far as I know, there is no way for the user to know when to freeze and thaw the time appropriately for React.

  11. samwgoldman commented on Jul 16, 2014

    @samwgoldman
    Contributor

    I think that the monkey patch to add a warning is a good idea, because I never want to call a non-pure function from inside render().

    Personally, I would thread a specific moment (possibly a Date instance) through props, but I appreciate many find that too cumbersome. For those people, maybe something based on context would be enough?

  12. syranide commented on Jul 16, 2014

    @syranide
    Contributor

    @samwgoldman Propagating the time through the hierarchy does not make sense. Theoretically, every component instance should update every microsecond. Time is ubiqutious. If your UI goes back in time, time would still continue forward, it simply does not belong in props IMHO.

  13. samwgoldman commented on Jul 16, 2014

    @samwgoldman
    Contributor

    @syranide Your opinion surprises me, considering React frames components as functions of props and state. The official docs even say that the render() method should be "pure." Depending on the current time is inherently impure.

    I also don't agree that component instances should update every microsecond. When would you want that? I could see a component that needed to update each second, but rendering should be sub-second (at worst), so it shouldn't be a problem to re-render with a new "moment" in props each second.

  14. syranide commented on Jul 16, 2014

    @syranide
    Contributor

    I also don't agree that component instances should update every microsecond. When would you want that? I could see a component that needed to update each second, but rendering should be sub-second (at worst), so it shouldn't be a problem to re-render with a new "moment" in props each second.

    If I'm making a precision timer or animations then I would want to update once for every screen refresh (which would be 60-120Hz and up), I would consider it unacceptable for the entire app to have to rerender or to settle for significantly less than optimal timer precision.

    A full rerender of a reasonably large app can take significantly long time, it is simply unacceptable to re-render the entire app. I also object to the idea of chosing an inferior implementation only to accommodate an interpretation of someone's subjective recommendation. To me, the very fact that you have to have make significant sacrifices to the fidelity of the value/time, to accommodate propagating it through the hierarchy, means that it is flawed.

    While I see the merits of sending all props up through the root, I'm not at all convinced that it is the end-all be-all. Treating components as isolated instances that only has access to circumstancially relevant data is fantastic for many reasons. But, it does not entail that being a transport for irrelevant data (from the perspective of the component) is inherently fantastic too.

    Food for thought, when you want to show an image, which of the following do you put in the prop:
    A. URL (resource identifier), which is "impure".
    B. The raw image data, which is "pure".

  15. samwgoldman commented on Jul 16, 2014

    @samwgoldman
    Contributor

    I'm curious to hear what others think about this. We seem to have a fundamental disagreement.

    Regarding your food for thought, I disagree that passing a URL is impure. Sure, the resource at the end of the URL may have changed, but that has nothing to do with the purity of render(). For render() to be pure, its output must depend only on its input. As long as render() doesn't actually dereference that URL to produce its output, it's still pure.

  16. Diggsey commented on Oct 8, 2014

    @Diggsey

    While pure components are nice, I think for time/rng it makes more sense to treat it as state:
    If you pass in the time using props, you're just shifting the state one level up - time is fundamentally global state so however far up the component hierarchy you push its state, it will still be in the wrong place.
    In addition, time is continuous, so it doesn't even make sense to use as state or props. IMO, the best way would be to have a prop which is a description of how to divide time into discrete "moment"s, and then local state should store the current "moment":

    <Clock freq="1Hz" />
    
    Clock = React.createClass({
        mixins: [React.TimeBased],
        render: function() {
            <span>{this.state.momentInTime}</span>
        }
    });
    

    In this case "React.TimeBased" would be a mixin that automatically called "setState" with frequency "props.freq". In addition, it can make sure that all components update synchronously application-wide where they have the same frequencies, to reduce the rate at which the DOM needs updating.

    In addition, when the time is converted into a human readable string, such as "2 days ago" which obviously doesn't need to update every second any more, it's really easy to use "shouldComponentUpdate" to prevent unneeded updates - just convert the two "moment"s to their string representations and see if they've changed.

    No need to monkey patch any built in functions, just make it clear in the documentation that this is the "right" way to do things, and that accessing global state in your own code is usually a sign that you're doing something wrong.

  17. samwgoldman commented on Oct 8, 2014

    @samwgoldman
    Contributor

    @Diggsey That's a really neat idea. I would love to see a proof of concept.

  18. syranide commented on Oct 8, 2014

    @syranide
    Contributor

    I have something like that already, including precise timeouts and dynamic units for elapsed/until. I should polish that up and NPM it perhaps.

  19. zpao commented on Oct 8, 2014

    @zpao
    Contributor

    Too controversial to be a good first bug, so let's get rid of that label.

  20. gaearon commented on Mar 18, 2016

    @gaearon
    Collaborator

    This has been inactive for over a year, and it doesn’t appear like there any plans to do this. With the explosion of JavaScript build tools and polyfills, we have been trying to be careful to not add surprises or touch the built-ins, and I think it has been the right call. React Native is actually running into some issues right now because of conflicting polyfills, and it’s great we’ve been able to avoid those so far by not touching the built-ins.

    I’m closing this but please let me know if I’m making a mistake and we should reopen. Thanks!

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Metadata

Metadata

Assignees

No one assigned

    Labels

    No labels
    No labels

    Type

    No type

    Projects

    No projects

      Milestone

      No milestone

      Relationships

      None yet

      Development

      No branches or pull requests

      Issue actions