You signed in with another tab or window. Reload to refresh your session.You signed out in another tab or window. Reload to refresh your session.You switched accounts on another tab or window. Reload to refresh your session.Dismiss alert
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?
This behavior is DEV only (so we don't double render in production builds) and should not affect how your component works so long as there are no side effects. 😄
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:
The output in console is:
My understanding is that before the component is rendered, the function under
useState
is called. The value returned by the function is assigned todata
, and thedata
values is used to render the component on the screen. The function underuseState
is called only once and we never callsetData
, 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.
The text was updated successfully, but these errors were encountered: