Home > Blockchain >  Why does changing Component props in App.js doesn't automatically refreshes it in browser when
Why does changing Component props in App.js doesn't automatically refreshes it in browser when

Time:12-26

I have just started to learn React and want to understand the difference in props and state behavior. I have two files App.js and Counter.js.

App.js:

import Counter from './Counter'

function App() {
  return (
    <Counter initialCount={2} />
  )
}

export default App;

And Counter.js:

import React, { Component } from 'react'

export default class Counter extends Component {
    constructor(props) {
        super(props)

        this.state = {
            count: props.initialCount
        }
    }

    render() {
            return (
                    <div>
                    <button>-</button>
                    <span>{ this.state.count }</span>
                    <button> </button>
                </div>
            )
    }
}

When I change initialCount in App.js and save file, it only changes in browser automatically if I have { this.props.initialCount } in <span></span>.

If I have { this.state.count } between spans (as in the code above), and try to change initialCount in App.js and hit save, then the value in doesn't change in browser. If I refresh the browser or change something in Counter.js after that and hit save (even adding simple space anywhere), then it updates the value without me having to refresh the browser.

I use Chrome and ReactDeveloperTools. From Components tab I can see that after I hit save in App.js, it changes props to the new value, but state is still the same.

It seems that constructor only called once. But I still don't understand this behavior.

CodePudding user response:

Component's constructor is only called once, when component is created. So when you for example change initialCount programmatically, Counter's constructor would not be called again.

This is a feature of Hot Reloading which does not recreate Counter component when you change props in App, but behaves as props of Counter component are changed programmatically.

CodePudding user response:

It seems like you are confusing two different things. One thing is a rerender on the change of data in React (say counter value changes onClick event) and the other is a manual change of hardcoded data in the application.

You seem to be describing a forced rerender with a change in your source code. It is most likely connected with the watcher tool that is set up by a tool that manages automatic updates during the development on a local server (Webpack / Create React App setup most likely). I tried to simulate in this sandbox but could not, as the counter value is always refreshed despite using state or props.

Also, FYI, beware of setting state with props. You can read this short post about it.

  • Related