1
function App() {
    const puzzles = [...Array(12)].map((_, i) => i).sort(() => Math.random() - 0.5);
    console.log(puzzles)
    return (
         <Game puzzles={puzzles} />
    );
}

const Game = (props) => {
    return <div>{props.puzzles}</div>;
};

I set a const rand array [puzzles] from 0 to 2 at App.js

then I pass the [puzzles] variable to the Game Component,

I console.log the [puzzles] at App.js and Game Component,

somehow the results are different.....

[1,2,0] log in App.js

[0,2,1] log in Component

It seen like the array is running again somewhere inside the JSX,

Can someone tell me if I missed anything? Many thanks!!!

Fan Lam
  • 11
  • 3
  • I think you'll need to provide your actual component code for folks to help – Nick Sep 20 '21 at 03:11
  • Your code looks good and works fine here, https://stackblitz.com/edit/react-hawtpd?file=src/App.js – Sanish Joseph Sep 20 '21 at 03:29
  • is there any other code that you haven't shared? – Sanish Joseph Sep 20 '21 at 03:34
  • 1
    @SanishJoseph it fails in Strict mode since the render phase should be pure (idempotent, no side-effects, etc) – Emile Bergeron Sep 20 '21 at 03:51
  • Does this answer your question? [Random number using React.js](https://stackoverflow.com/questions/45175836/random-number-using-react-js) – Emile Bergeron Sep 20 '21 at 04:02
  • @EmileBergeron After I change the to Fragment mode, the problem had gone! If I want to keep using Strict mode, where do I need to modify my code? – Fan Lam Sep 20 '21 at 04:05
  • Yes, you should change your code to something similar to the question I linked, or just using state would help. Render should be pure, as soon as the app re-renders, a new puzzle will be generated and it becomes unpredictable. – Emile Bergeron Sep 20 '21 at 04:07
  • 1
    @EmileBergeron Ok I try to change it to state, many thanks! – Fan Lam Sep 20 '21 at 04:22
  • @EmileBergeron good to know that things behave differently in strict mode. – Sanish Joseph Sep 20 '21 at 04:34
  • @SanishJoseph Strict mode is a safe guard against these types of bugs, it runs the render cycle twice with the same input and it highlights situation where the rendering isn't pure, like in this question. Strict mode should behave identically, except when there's a potential bug in the components code. – Emile Bergeron Sep 20 '21 at 16:17
  • 1
    Interesting. I am using `` in my projects and I never knew it had such a logic behind. Yes I used to get warnings especially from MUI 4. Thank yo for explaining. – Sanish Joseph Sep 20 '21 at 16:37

0 Answers0