Photo by Ferenc Almasi on Unsplash
Variables vs States in React.js
why do we use state in React.js instead of a simple variable?
1 min read
When I was interviewing candidates for the entry-level react developer position. I was thinking of asking basic questions like “what is this particular thing in react.js or why do we use this particular thing in react.js and its significance?”.
One of those questions was "why do we use state in React.js instead of a simple variable?"
To my surprise, most candidates were unable to answer this question correctly. Their guess was “The application wouldn’t work like it is working but I don’t know why.”
The significance of state
In React, we use state instead of simple variables because when a component's state changes, React automatically re-renders the component to reflect these changes in the UI. React components are designed to be "reactive," meaning that they automatically update in response to changes in their data. This is why React uses state instead of simple variables: state makes it easy to keep the component's UI up-to-date with changes in the data, while simple variables do not have this capability.
The main thing here is to know that a change in the state data triggers the re-rendering of the component while this is not the case with simple variables.