Managing State
- React is not aware of any local variable declared inside the function and any changes to it
- You have to tell react; the component will have data/state which will change overtime
- A hook is a function that allows us to tap into built-in features in React.
- Using state hook we can tell react that the component will have data/state which will change overtime
- useState takes initial value as parameter and returns array. First element is variable and Second element is a updater function to update the variable.
- React will be notified when updater function is called. It knows state changed so it will re-render component and DOM will be updated.
- In react we never update the DOM directly
- Each instance of component will have its own state
- Import
useState
import {useState} from "react";
- Call
useState
to declare state
const [selectedIndex, setSelectedIndex] = useState(0);
<ul className="list-group">
{items.map((item, index) => (
<li
className={
selectedIndex === index
? "list-group-item active"
: "list-group-item"
}
key={item}
onClick={() => setSelectedIndex(index)}
>
{item}
</li>
))}
</ul>