HomeToolsAbout a20k

useState

What is it

Adding a state variable to the component.

Why need state variable

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:

  • Local variable does not persist between renders.
  • Change to local variable does not trigger re-render.

Dedicated state in a components provides:

  • state variable to retain the data between renders
  • state setter function to update the variable and trigger React to render the component again

Return value

The setState function has a return value of void (does not have a return value).

  • Sets the state to a new value
  • Triggers a re-render

Lift the State Up

Always lift the state to the top of the parent when the state logic influences the parent component also

  • Pass the state and the setState action down to the child as a prop instead

If 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} /> ) }
© VincentVanKoh