DEV Community

Cover image for How to reset React Component State by itself
Vamshi Krishna
Vamshi Krishna

Posted on • Originally published at vamshi.nl

How to reset React Component State by itself

A react component state (defined by useState) remains unchanged during renders and is affected only when manually changed. One common way to reset the state is to manually modify them:

const Demo = () => {
  const [name, setName] = useState('default');
  const [address, setAddress] = useState(null);

  const reset = () => {
    setName('default');
    setAddress(null);
  }

  return (
    ...
    <button onClick={()=>reset()} >Reset</button>
  );
}

Enter fullscreen mode Exit fullscreen mode

This is not ideal for three reasons:

  1. The initial state is repeated and we may need to extract it to another variable to prevent bugs mismatch
  2. Need to keep both in sync while updating
  3. If the state is added from a custom hook, we have no way to reset it directly from the component

A better way is to reset by adding a special prop called key. It's well known we need to pass key while mapping list of components. But it can also be used to reset the component state. But this involves adding a new state to parent component just for resetting child component.

  const Demo = ({reset}: {reset:()=>void})=>{
    const [name, setName] = useState('default');
    const [address, setAddress] = useState(null);

    return (
      <button onClick={()=>reset()}>Reset</button>
    );
  }

  const Parent = ()=>{
    const [resetKey, setResetKey] = useState(0);

    return (
      ...
      <Demo key={resetKey} onReset={ ()=> setResetKey(resetKey+1)} />
    )
  }
Enter fullscreen mode Exit fullscreen mode

What we are doing here is forcefully changing the value of prop key which resets the component state manually. Technically its not doing it by itself but taking parent component help, but this seems to be the cleanest way to reset.
This has the disadvantage of rerendering parent component and all its children. But since no other state is changed, ideally it should not be a big deal.

Codesandbox to play with :

Top comments (0)