State in React Component

We call ReactDOM.render() whenever we want to update the UI with new state.

When we load the page first time in the browser it’s ok to call ReactDOM.render() because it allows us to render everything that we want to load on UI.

However, when you want to re-load only the part of the UI or want to reflect the change only in single component then you wouldn’t want to call the ReactDOM.render() because it will render the whole UI again and its not very efficient.

This is where the State of Component comes in picture. State of Component allows us to update only the part of UI which is updated due to some action or when some condition is met.

Consider the below example —

The above code translates on the screen like this -

On click of button, Hello!! is toggled.

If you observe Line 6 of code, we have something called state, this state can contain different variables; in our case, the state contains toggle variable which is used at Line 23 to show and hide Hello!! on screen.

The function switchToggleState() allows us to change the state of the component, when we update the variable toggle with that function, the state changes which in turn causes the screen to toggle the <h1> at Line 23.

The change in state is what saves us from re rendering the whole UI.

10/100

--

--

Get the Medium app

A button that says 'Download on the App Store', and if clicked it will lead you to the iOS App store
A button that says 'Get it on, Google Play', and if clicked it will lead you to the Google Play store