State
What is “State” in React?
State = memory of a component
whenever an interaction happens, component need to change and show the latest data after an interaction
It stores values that can change over time and should be shown in the UI.
To update the UI, components first need to “remember” these things: the current input value, the current page, and the current contact list
Local variables do not trigger re-renders,React would not detect a state change and would not re-render our component.
Why we need State?
State solves both problems:
Keeps value (doesn’t reset)
Automatically updates UI
What happens now?
Click button
setCount(count + 1) runs
React updates value
Component re-renders
UI shows new count
summary
Normal variable
→ resets + no UI update
State
→ remembers value + updates UI
useState
- Is a React Hook useState() is a React tool (hook) used to store and update data in a component state variable, is a special variable that is capable of retaining data between renders. setter function to update the state variable and hence trigger a re-render of our component The useState() hook takes in the initial value of the state variable as an argument and provides us with the state variable and the setter function. The variable could be of any data type, such as string, number, object, array, and more. State hooks like useState and useReducer enable functional components to manage state. useState is used to declare state variables in functional components. The state variable (count) and the updater function (setCount) allow you to read and update the state.
state: The current value of the state.
setState: A function used to update the state.
initialState: Can be a primitive type or an object/array
Updater functions
This setter function can be called anything.
the setter function will always have access to the value of the state variable in the current render.
to access the latest value of a state variable and update it in that case you can use updater functions
instead of passing a value to setCount we passed a function, this function gets the latest value of the variable as a parameter and returns an incremented value
Using array/object as State
Instead of creating three different state variables, it would be better to create an object that stores the state of a person. We can combine name, age, and hobby properties into an object state
numbers, and strings as state variables, these JavaScript values are “immutable”, so if we replace them we can trigger a re-render.
we cannot mutate a state variable of type objects/arrays. We always need to replace them entirely or use the spread operator.
When updating the array state, we must avoid methods like push, pop, shift, unshift, splice, reverse, and sort as these methods mutate the original array. Instead, we should use options like concat, spread syntax ([...arr]), filter, slice, and map as these methods return an entirely new array.
Caveats
useState is a hook, so just like any other hook, we should only use the useState() hook at the top level of our component: We should not use it inside any function, loop, nested function, or conditions. This helps React preserve and call hooks in the same order each time a component renders.
- Add state variables to Functional component
- Enables components to remember information (Like user input or Counter value) between renders and triggers re-renders when the data changes.
- useState is imported from React library and call it at the top level of your component
- useState() hook can hold strings,arrays,numbers,objects etc..,
- using useState to keep track of the application state
- State refers to application data or properties,need to be tracked.
- State refers to Component memory
- useState : In functional component,we have no 'this'.we can't assign or read 'this.state'.Instead,we call useState Hook directly inside our component.
- Variables "disappear" when the function exists but state variables are preserved by React.
import {useState} from 'react';
Concepts
Triggers Re-renders : By calling the "set" function tells React state has changed.
Re-rendering the component for reflect the new data.
Asynchronous Updates: State updates are not immediate.
Batches updates for performance,means new value is available only in the next render.
Functional Updates: New State depends on the Previous State.
Pass a Function to setter to ensure that they are working with the most recent value.
setCount(prevCount => prevCount + 1);
Immutability with Objects/Arrays: State is object or array,you must replace it rather than mutate it.
Use JavaScript Spread Operator to create a copy
How does useState() work?
Handling and managing State in your applications.
takes first(initial) value of the state variable as its argument.
second value ,sets your State (setState).
const[count,setCount] = usestate(initialvalue)
First render,it returns the initial state.
Re-render - updates to different value using Set function.
Example 1: Conditional Rendering with the useState() Hook
Update State depending on two conditions.
if the user is logged 'in' or 'not'.
initial State -> set to false
-> user is not logged in.
Conditional(ternary operator)
Takes three operator
A condition followed by question mark(?)
An expression to execute if the condition is truthy followed by colon(:)
An expression to execute if the condition is falsy.
Alternative to an if...else statement.
Example 2: How to use the useState() Hook in a form in React
- Set an empty state,that uses the set Function what the user type in as their input.
- Want to collect the name and email of users through a form and submit.
- Use useState hook to set the name and email to 'null',wait for user to input their details.
- create an arrow function with the "handleSubmit",executes the preventDefault() method.
- "Console.log" : To display the name of user and email,get details using onSubmit() event handler.
- Use the 'set' Function for name and email to target a change in input and get value of input initialised as "user" and "email".
- useState hook uses the set function for re-rendering ,you are re-rendering the new values,the user has added in the form.
- Setting the value in your input as value ={user}.
Pass to useState as an argument
The only argument to the useState() hook is the initial state.
The state doesn't have to be an object.
A number/string if that's all we need.
Want a number for how many times the user clicked,so pass '0' as initial state for variable.(want to store two different value in state,call useState() twice.)
What does useState Return ?
Return a pair of values
- The current state
- A function that updates it.
const[count,setCount] = useState()
similar to 'this.state.count' and 'this.setState' in a class.
React will remember its current value between re-renders,provide recent one to function.
Want to update the current count,we can call setCount.
Why is useState not named createState instead ?
Create is not used because
State is only created first time our component renders.
During the next renders,useState gives us the current state
This is reason for Hook name start with 'use'.
If not given,it is not a state.
Reading State
Want to display the current count in class,we read 'this.state.count':
<p> You clicked {this.state.count} times </p>
In a function,we can use Count directly.
<p> You clicked {count} times </p>
Updating State
In a class,need to call 'this.setState()' to update the 'count' state.
In a function , we already have 'setCount' and 'count' as variables so we don't need 'this'.
Declare a State variable , we must used inside square brackets
const[count,setCount] = useState(0);
Declare a state variable with useState,it returns a pair - an array with two items.
The first item is the current value.
The second item is function,to update it.
Using Multiple State Variables
Give different names to different State variable, we want to use more than one:
function ExamplewithManyStates(){
const[age,setAge] = useState(42);
const[fruit,setFruit] = useState('banana');
const[todos,setTodos] = useState([{text : 'Learn Hooks'}]);
}
we have age,fruit,todos as local variables, we can update them individually.
function handleOrangeClick(){
setFruit('Orange');
}
You don't have to use many state variables.State variables can hold Objects and arrays ,you can still group related data together.
Updating a state variable always replace it instead of merging it.
'State' refers to data/properties ,need to be tracking in an application.
Import useState
use the useState Hook,first need to 'import' it into our component.
At the top of your component,import the useState Hook
import {useState} from "react";
Destructuring useState from react as it is 'named export'
Initialise useState
initialise our
Top comments (0)