score:1
your ternary is checking the state for showfirstcomponent
and rendering only one.
{this.state.showfirstcomponent ? c1 : c2}
if you remove that all together, and just do
<simplecomponent number="1" />
<simplecomponent number="2" />
you'll get two logs. to further answer the question, constructor
is called when the component is mounted, so usually once, unless you're dynamically mounting stuff. to get back at your ternary:
{this.state.showfirstcomponent ? c1 : c2}
if you were to toggle this.state.showfirstcomponent
with a button lets say:
<button onclick={() => this.setstate({
showfirstcomponent: !this.state.showfirstcomponent
})>
toggle c1/c2
</button>
every time you hit this button, component will be unmounted, and another one mounted, so you'll get a console log. here's the order of react lifecycle methods between mount and unmount. however, if you do anything else, eg change the props passed, change the internal component state of <simplecomponent />
, it will not unmount, but rather, update, which calls the render method, and not the constructor. i suggest adding a console.log
for some lifecycle methods in your <simplecomponent />
and trying to trigger them, to better understand the component lifecycle. or read an article about it.
score:2
if someone has landed here for react-native.
assigning different keys
for different instances will create new instances instead of reusing the same instance.
<mycomponent
key={this.state.uniqueinstancekey}
mydata={this.state.mydata}/>
score:4
according to the doc, constructor
is only called before a component is mounted. if you add two more react lifecycle functions to your code example: componentdidmount
and componentwillunmount
, you'll see that the component only mounted once in the entire process, regardless of the times the state changes. if you then add shouldcomponentupdate
to the component, you'll see that there is only one instance of simplecomponent
and the upper-level state change is shown as props change on simplecomponent
.
the reason why you don't see two instances mounting and unmounting here is that variables c1
and c2
are not instances of simplecomponent
as commonly and conveniently assumed. instead, they are reactelement, which is a description of the component instance.
the primary type in react is the reactelement. it has four properties: type, props, key and ref. it has no methods and nothing on the prototype.
only when the element gets rendered, an instance of the component gets created and constructor
and the lifecycle functions get called at their respective time points.
so then why, as in your example, the element c2
never gets to be used to create a component? this goes back to how react decides when and what to update at a certain time (you can read more about it here:
when a component updates, the instance stays the same, so that state is maintained across renders.
in your example, when the app
component renders c2
instead of c1
, react sees that the new component element is the same as the old one so it reuses the component(i.e. only a single instance exists) and updates the props/states accordingly.
here are some more readings that i find useful to understand this problem: https://developmentarc.gitbooks.io/react-indepth/content/life_cycle/birth_mounting_indepth.html
mark amery's answer to this question is also very helpful.
Source: stackoverflow.com
Related Query
- When does React create a new component instance?
- React component create a new instance of the state when re-rendering even the state is not changed
- React Router Dom & Firebase Auth: history.push changes url but does not render new component when called after firebase auth create account
- Create a new MobX store instance for a React function component
- React Router "Link to" does not load new data when called from inside the same component
- Does re-render of a component create a new instance of its child component?
- How do I create a class decorator for mixing new methods into a React component when using Typescript?
- How to create a new instance react component
- React component render is called multiple times when pushing new URL
- Best way to create new React component using create-react-app
- How does useState() in React Hooks know which Component instance it is?
- When does React create SyntheticEvents?
- When React functional component re-render, does it reassign assigned values & functions?
- Property does not exist on React component when defined with recompose
- React - How change state of single component when there are multiple instance of same component?
- How to attach a compound component when using React forward ref (property does not exist on forwardRefExoticComponent)
- How to force React (functional component using hooks) to create a new component from scratch on props change?
- Why does the render function in react is called twice when using the component strategy?
- Why React component get re-rendered only once when state does not change?
- Embedded child component doesn't get changed when I click a new one with React Router
- React - Display new component when form is submitted
- Why does the component is not re-rendering when i add @action decorator to an react event handler function
- React create new component instantly
- React jsx array component does not re-render when state changes
- React — have active item state stay with menu component when loaded into new page
- React test passes but component does not work properly when state updated in document.addListener handler
- Passing function to create new component to child using react hooks
- React router Redirect does not work when route comes from another component
- Create a new row through a rendered React component
- Why does my React component display incorrect data when filtering by values controlled by useState()?
More Query from same tag
- Calling ReactDOM.render more than once
- React Redux: redirect user (history.push()) when certain http status codes are received during async action (thunk)
- calculated value of a var does not affect in pie chart in react
- Differences in arrow function and no arrow function in ReactJS?
- Webpack mode & loader issue
- how to change icon size in googleMap ,react integration
- React set background color with state rgb
- Placing default value
- React JS Error after requiring ReactRouter - Warning: React.createElement: type should not be null, undefined, boolean, or number
- how can we replace span contenteditable in regex?
- Passing one component to another in react.js
- How to add a video to React Responsive Carousel Npm Package?
- React, loading a script inside a form (mercadopago)
- jest.mock invariant variable access: __extends
- How to fix this error:Uncaught (in promise) TypeError: this.state.arrdata.map is not a function
- React setState prevState parameter and Array#map
- How to Resolve Interdependency Between Apollo's Mutation and Formik Render Props?
- data not getting passed on clicking submit in material-ui react login form
- ReactJS Koans Grocery-list part 1
- Build error occurred ReferenceError: describe is not defined > During now.sh deployment
- posting form data with Axios to .NET API
- How can I delete the item if it is stored as an array in reactjs?
- how to render an array of objects in React
- React conditional update setState on basis of previous values, if state value is true make it false and vice versa
- Missing Patch method with corsheaders only on chrome
- How to apply styles to props of multiple classes?
- cannot set state with gatsby react Unhandled Rejection (TypeError): Cannot read property 'setState' of undefined
- How to format text and embed a video with Quill?
- Axios without a full URL
- Why Is My React Bootstrap CSS Not Working?