Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Is it possible to "initialize" a React component?

So basically I’m trying to implement a restart function for my game, and I would like to be able to somehow "reload" my GameView component. Here’s the lifecycle: 1. React renders/mounts my component 2. user interacts with the component and it changes 3. now, I want to call a function to basically wipe off all those changes and bring the component (and all of its child) back to its state in step 1. Here are 2 possible solutions I’ve thought of:

  • keep the same component and set all the state variables back to their initialized values
  • make a new component and replace the old one

The first is not very practical since it gets very complicated when child components gets involved and the second doesn’t work because apparently React still views the new component as being identical the old one since they have the same props? I’m not sure why but I couldn’t get it to work.

I would greatly appreciate some help!

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

>Solution :

You can use a key to force react to unmount and remount the component. Keys give react additional information about which element from one render corresponds to which element from the next render. If the keys are different, then this tells react they are different elements, even if they have the same type.

const App = () => {
  const [gameNumber, setGameNumber] = useState();

  const resetGameView = () => {
    setGameNumber(prev => prev + 1);
  }

  return (
    <div>
      <GameView key={gameNumber} />
    </div>
  );
}
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading