Skip to content

Bug: It seems that the default value in functional React component gets updated after render. #20851

Closed
@DSamuylov

Description

@DSamuylov

It seems that the default value in functional React component gets updated after render.

React version: 17.0.1

Steps To Reproduce

I created a question on StackOverflow: https://stackoverflow.com/questions/66286856/why-default-value-in-functional-react-component-gets-updated-after-render, but also repeat it here:

const MyComponent = () => {

  // Initialise data with a random value:
  const [data, setData] = React.useState(
    () => {
      const data = _.sampleSize(_.range(5), 3)
      // Print data on initialisation:
      console.log('init data in default:', data)
      return data
    }
  )

  React.useEffect(() => {
    // Print data after the component is rendered:
    console.log('init data after render:', data)
  })

  return (
    <div>{data}</div>
  );
};

The output in console is:

[Log] init data in default: – [0, 3, 1] (3)
[Log] init data after render: – [2, 1, 3] (3)

My understanding is that before the component is rendered, the function under useState is called. The value returned by the function is assigned to data, and the data values is used to render the component on the screen. The function under useState is called only once and we never call setData, so the value should be the same. Maybe I miss something?

Link to code example:

https://codesandbox.io/s/jovial-glade-9jm75?file=/src/App.js

The current behavior

The output in console before and after render is different.

The expected behavior

The output in console before and after render should be the same.

Metadata

Metadata

Assignees

No one assigned

    Labels

    Type

    No type

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions