Home > Mobile >  Is it possible to "initialize" a React component?
Is it possible to "initialize" a React component?

Time:05-17

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!

CodePudding user response:

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>
  );
}
  • Related