Skip to content

Bug: React hook state not cleared when rendering using ReactDOMServer if component errors #19211

@pmaccart

Description

@pmaccart

In the react-dom package, React maintains some global internal state for hooks when server rendering a component (https://github.com/facebook/react/blob/v16.13.1/packages/react-dom/src/server/ReactPartialRendererHooks.js#L44-L54). The state is reset after each function component finishes rendering via the finishHooks function.

Since the state of the hooks are only reset after a component finishes rendering, we can observe incorrect hooks state if a component that was using hooks raised an error while rendering, thus causing the finishHooks call to never execute. The next function component to render within the same process would then use the hooks state from the Component that previously failed to render, potentially causing mismatches.

We can work around this bug by rendering a no-op function component at the top of our react tree (which will cause finishHooks to properly run), but it seems like a more ideal fix would be to reset the hooks state as part of the prepareHooks call. The comments actually have the code already present -- maybe there is a good reason for the state not to be reset there?

React version: 16.13.1

Steps To Reproduce

Refer to the steps in the README of the example repo.

Link to code example:
https://github.com/pmaccart/react-hooks-ssr-state-leak

The current behavior

The hooks state of a component is not cleared between renders

The expected behavior

The hooks state of a component is cleared between renders

Metadata

Metadata

Assignees

No one assigned

    Labels

    Status: UnconfirmedA potential issue that we haven't yet confirmed as a bug

    Type

    No type

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions