React tips pt.1 ✨ key

·

1 min read

You’ll often see the key attribute when rendering lists in React. However, it also serves another purpose You can reset the state of a component or force re-rendreing by assigning a new key to it. In this instance, the Reset button modifies the version state variable, which is used as a key for the Form component. When the key is changed, React re-render the Form component (along with all its children), effectively resetting its state. a simple and effective way to reset the state :)

import { useState } from 'react';

export default function App() {
  const [version, setVersion] = useState(0);

  function handleReset() {
    setVersion(version + 1);
  }

  return (
    <>
      <button onClick={handleReset}>Reset</button>
      <Form key={version} />
    </>
  );
}

How its work?

All elements in React have keys but we see them often in lists, React adds keys to all elements in the background, and React uses keys for identifying and rendering those changes in the virtual DOM.

If we change the component key, React considers it a new component and re-renders it, and all its states are cleared. In essence, the component is re-rendered.

You can use this trick to reset the form state or force re-rendering a component.