Adding a state variable to the component.
Component needs to maintain a state
when display on the screen needs to change as a result of an interaction.
Why we can't rely on local variables on a component to act as a state:
Dedicated state in a components provides:
state variable
to retain the data between rendersstate setter
function to update the variable and trigger React to render the component againThe setState
function has a return value of void
(does not have a return value).
Always lift the state to the top of the parent when the state logic influences the parent component also
state
and the setState
action down to the child as a prop insteadIf the child component state has nothing to do with parent component, state, or logic, then it can remain independently in the child component
export default function Parent(){ const [someState, setSomeState] = useState(); function setStateAction() { setSomeState(); } return ( <Child parentState={someState} stateAction={setSomeState} /> ) }