React JS 19 Tutorial in Hindi #44 Derived State in React.js

What is drived state

Understand drived state with example

How it improve performance

Interview Question

Derived state is not directly stored using useState. Instead, it is calculated based on:

  1. props
  2. other state values

So instead of duplicating data in state (which can lead to bugs), you derive it when needed.

import { useState } from "react";

function App() {
const [users,setUsers]=useState([]);
const [user,setUser]=useState('');
const handleAddUsers=()=>{
setUsers([...users,user])
}
const total=users.length;
const last= users[users.length-1];
const unique= [...new Set(users)].length

return (
<div>
<h2>Total User : {total} </h2>
<h2>Last User : {last}</h2>
<h2>Unique Total User : {unique}</h2>

<input type="text" onChange={(event)=>setUser(event.target.value)} placeholder="add new user" />
<button onClick={handleAddUsers} >Add User</button>
{
users.map((item,index)=>(
<h4 key={index}>{item}</h4>
))
}
</div>

);
}

export default App;