useState
When a state value is changed, it triggers react to create another render.
Note that state must be defined at the top level of a component.
import { useState } from 'react';
import { sculptureList } from './data.js';
export default function Gallery() {
const [index, setIndex] = useState(0);
let sculpture = sculptureList[index];
return (
<>
<button onClick={() => setIndex(index + 1)}>
Next
</button>
<h2>
{sculpture.name}
</h2>
</>
);
}
State is a snapshot of the current renders values. The value of a state cannot change without triggering a re-render. So in a sense it is a snapshot of the UI.
State is a fundamental part of react, and state is stored within the react framework.
Local variables and handlers do not survive a re-render. Hence if you change state and attempt to use that changed state within the same component; you will only ever access the old value.
So in other words consider handlers a part of that snapshot of the UI’s state.