Before diving into state variables, let's break down what makes a React component tick!
What is a React Component?
In React, a component is a reusable piece of code that represents a part of your user interface (UI). It can be as simple as a HTML button or as complex as a complete page.
What are State Variables in React?🤔
In React, a state variable is a special type of variable that stores data specific to a component.
Why Do We Need State Variables?🤷
In React, Components are the building blocks of React applications. They can be functional or class-based. When we say functional component, they typically return Node or JSX elements (a special syntax that looks like HTML but is actually JavaScript code). To display content on browser, React simply calls the functional component, rendering the elements. Each time a component/function get called/renders its variables are re-declared and re-initialized. This prevents the component from retaining any changes made to its data. Normal JavaScript variables are insufficient because they don't persist across re-renders (function call).
One potential solution is to use global variables and pass that as an parameter to react function but this can lead to tight coupling, making code harder to understand, test, and maintain.
To address this issue, React team came up with a solution 🎉 called state variable.
Use a state variable when a component needs to “remember” some information between renders. State variables are declared by calling the useState Hook.
These variables allow React components to manage and store data that changes over time. Unlike normal variables, state variables are by default immutable and can only be updated by their state updater function. This function trigger a re-render of the component whenever their value changes. This dynamic behaviour enables React components to return active data updates and provide an ideal user experience. React keeps track of changes made to state variables. When a change is detected, React automatically re-renders the DOM tree using a process called reconciliation.
Ready to Dive Deeper?
Additional Resources:
State a component's memory
Hope this helps! Let me know if you have any questions or need further clarification. Share your feedback and suggestions.
Top comments (1)
Well explained