Introduction
As we discussed in the previous blog, each component in React has data- props & state. Props are the one that can be passed from parent component to child, they cannot be mutated and is unidirectional(cannot be passed to parent). Now we will be focusing on states.
States
The dynamic data in a component is represented by State, when these states are updated, react automatically rerenders the particular component to keep the UI in sync with updated data. In simple words, if we change the state we change the UI.
Recap
Creating State variable
Import useState() function from react
import {useState} from 'react'
When we call this useState() we send the initial value of the variable in the argument
useState(1);
(In this example, 1 is the initial/default value of the state variable)This useState() function returns an array, It has 2 elements, 1st element is the default value of the variable, and 2nd element is the setter function to update the state variable.
So the array can be destructured and the state variable & setter function can be extracted
const[step,setStep]=useState(1);
(in this example, step is the state variable and useStep is the setter function to update the state.The state variable is used in JSX, we no longer need DOM manipulation as components are built on the reflection of state changing over time.
Now to update the state, we can add an event listener which when triggered calls a function, where the setter function is called and the updated state is passed in the argument,
setStep(step+1)
Now when the state is updated, the entire component is rerendered by
๐คFOR NERDS: useState is a Hook in react, Hooks start with the use keyword (useEffect, useReducer)
Enough Talking, now let's understand with an example- we need to make a tracker, every time we press a button the value increments by one.
Code:
import "./styles.css";
import { useState } from "react";
export default function App() {
const [count, setCount] = useState(0);
return (
<div className="App">
<h1>Counter</h1>
<p>{count}</p>
<button onClick={incCount}>Click Me</button>
</div>
);
function incCount() {
setCount(count + 1);
}
}
Here we set up a state variable count and it's used in JSX, when the event listener is triggered(button is clicked), setCount function is called, and the updated value in its parameter.
Why is React called React?
State is the fundamental principle of React, we update the UI by changing the state, and REACT REACTS to this change and rerenders the particular component.
Therefore we can say, that React is all about changing state over time (Declarative approach). It simplifies the process of managing UI updates, allowing developers to focus on designing the desired behavior and letting React take care of efficiently updating the components accordingly.
React allows components to be reactive and updated in response to changes in state. This reactive nature of React is what gives it its name.
Can we update the state variable manually?
Instead of using, a setter function what if we try to update the state variable? No. In that case, the data will be updated but will not be reflected in the UI.
function incCount() {
count=count+1; // WRONG WAY
}
THIS EXAMPLE IS COMPLETELY WRONG, we don't get any error but the UI is no longer in sync with that data. If we click the button the data will increase but will not be reflected on the UI
We need to understand the UI is rerendered only when the setter function is called, it's a functional way of updating rather than mutating.?
Correct Way to Update State
When we are updating the state based on the current value of the state (ex-incrementing counter) we send a callback function and inside the arrow function, we do the necessary update.
function incCount(){
setCount((count)=>count+1);
}
React's callback-based state updates provide a reliable and efficient mechanism for managing state changes, guaranteeing that the UI reflects the desired behavior accurately and consistently.
Multiple State
States are the memory of components, and they are maintained through the course of the web app, in this course the component is rerendered multiple times due to changes in one state, but the state of other variables is maintained throughout the process.
Let's take an example, Here like the above counter, we have 2 counters with 2 different state variable
import "./styles.css";
import { useState } from "react";
export default function App() {
const [count, setCount] = useState(0);
const [count2, setCount2] = useState(0);
return (
<div className="App">
<div className="counter">
<h1>Counter A</h1>
<p>{count}</p>
<button onClick={() => setCount(count + 1)}>Click Me</button>
</div>
<div className="counter">
<h1>Counter B</h1>
<p>{count2}</p>
<button onClick={() => setCount2(count2 + 1)}>Click Me</button>
</div>
</div>
);
}
In this scenario, each time we click a button, the corresponding counter increments. As the component is rerendered, the entire component is updated while preserving the state of the other counter. To illustrate, when counter A is increased, counter B remains unchanged and unaffected.
Lifting Up State
Whenever multiple sibling components are required to access the same state, it is lifted out to the first common parent combination, Context API solves this problem by creating a context and consuming it wherever required.
Derived State
When dynamic data can be extracted from an existing piece of state, we don't need to define another state, coz everytime its updated, the component is rendered and the derived state is also extracted from the updated state.
Props vs State
Props | State |
Props are External data of a component | The state is the internal memory of a component |
It's passed from the parent component to the child component | It is owned by the component itself |
It is read-only data and cannot be updated | They can be updated using a setter function, which results in the rerendering of component |
It is used by the parent component to configure the child component | It is used to make components interactive |
Conclusion
In conclusion, state variables are used in the dynamic components (i.e the interactive part), Whether it's handling user input, tracking progress, or updating content based on external events, state variables provide the foundation for creating interactive and responsive components in React.
I hope this blog, gives a basic idea of States
And yeah Congratulations! you fall into "The cooler Daniel" category from now on.
Till Next Time!
Connect With Me ๐
If you're interested in topics like React.js, JavaScript or Web Development in General, Let's Connect!
LinkedIn: Click Here
Twitter: Click Here