Andy's blog

If you always do what you've always done, you'll always get what you've always got.

0%

筆記-Preserve and Reset State

前言:
紀錄一下 React 筆記。


參考資料:


React will create React Tree, it make React Dom by JSX
react_dom

Recap

  1. React will preserve state when position not change(React Dom Tree not change place)
  2. If you want to reset or update you can give key or put component in different structure
  3. If you destroy component,React will reset state value
  4. We should not contain components in another components
    This is because inside components every time will cause reRender issue and otherwise state will not keep anymore
    This leads to bugs and performance problems.
    Just like below
    1
    2
    3
    4
    5
    6
    7
    8
    9
    10
    11
    12
    13
    14
    15
    16
    17
    18
    19
    20
    21
    22
    23
    24
    25
    26
    import { useState } from 'react';

    export default function MyComponent() {
    const [counter, setCounter] = useState(0);

    function MyTextField() {
    const [text, setText] = useState('');

    return (
    <input
    value={text}
    onChange={e => setText(e.target.value)}
    />
    );
    }

    return (
    <>
    <MyTextField />
    <button onClick={() => {
    setCounter(counter + 1)
    }}>Clicked {counter} times</button>
    </>
    );
    }

    codesendbox
  5. Don’t nest component definitions, or you’ll reset state by accident.