dec-15th [keys in list and rendering list using state]
dec-15th [keys in list and rendering list using state]
When rendering lists of elements, React requires a key prop to help identify which items have
changed, been added, or been removed. This is crucial for performance optimization and to help
React track the elements more efficiently.
Efficient Reconciliation: React uses the key prop to optimize the re-rendering process
when the list changes (e.g., when an item is added or removed).
Uniqueness: Keys should be unique among siblings (items in the same list) to ensure
React can properly track them. This helps React avoid unnecessary DOM operations and
makes sure that only changed elements get updated.
function App() {
const fruits=["Apple","Banana"]
return (
<div>
{fruits.map((x,index)=><li key={index}>{x}</li>)}
</div>
)
}
function App() {
const fruits=[
{
id:1,
name:"Apple"
},
{
id:2,
name:"Banana"
}
]
return (
<div>
{fruits.map(x=><li key={x.id}>{x.name}</li>)}
</div>
)
}
States in functional Components:- In React, functional components are the more modern
and recommended way of defining components. With the introduction of React Hooks (starting
from React 16.8), functional components can now use state, which was previously only available
in class components.
The main hook used for managing state in functional components is useState.
Here’s an in-depth look at how states work in functional components using the useState hook:
function App() {
const [count, setCount] = React.useState(0)
function Increment(){
setCount(count+1)
}
return (
<div>
<h1>{count}</h1>
<button onClick={Increment}>Increment</button>
</div>
)
}
You will need a state to hold your list of items and a way to update it. You can use useState to
define and manage the state.
Eg: Let us try to create and render a list using state and then try to update the state.
function App() {
const[list, setList] = React.useState(["Apple","Banana"])
function Orange(){
setList([...list,"Orange"])
}
return (
<div>
{list.map(x=><li>{x}</li>)}
<button onClick={Orange}>Add Orange</button>
</div>
)
}