0

Here is the code , no idea why Mem re-render after set state, as it is a memoized component, or if i wanna remember the component with set state, i should use useRef? that stupid??


const Demo = () => {
    console.log("render")

    const data = LoadSomeData();

    return (<>{data.id}</>)
}

const Mycomp = ({...props}) => {

    const [showSearch, setShowSearch] = useState(false);

    const Mem = useMemo(() => <Demo />, [props.iwandToReloadData]);

    return (
        <>
        { showSearch ? 
            <button onClick={()=>setShowSearch(false)}>Back</button>
        :
        <>
            {Mem}
            <button onClick={()=>setShowSearch(true)}>Search</button>
        </>
        }
        </>
    )
}

export default Mycomp;

user192344
  • 1,274
  • 6
  • 22
  • 36
  • 2
    Because you conditionally render `Mem ` so when `showSearch ? ` is true the `Mem ` is unmounted, when `showSearch ? ` is false, it's re-created (not re-render) again. – Tony Nguyen May 28 '20 at 04:00
  • oh finally someone tell me why , and i got it – user192344 May 28 '20 at 04:03
  • I am glad it helps you. – Tony Nguyen May 28 '20 at 04:05
  • Another thing to remember is that the ***entire*** body of a functional component ***is*** the "render" function, and react can call "render" nearly any number of times (*paused/aborted/restarted/etc...*) it needs to during the render phase in order to compute a diff to know what needs to be flushed to the DOM during the commit phase. [React lifecycle diagram](https://projects.wojtekmaj.pl/react-lifecycle-methods-diagram/) The console log in the body of the function isn't an accurate measure of when a functional component is *actually* rendered, use `useEffect` instead. – Drew Reese May 28 '20 at 04:29

1 Answers1

0

Refer to the comment from Tony Nguyen, it is because i use conditional render for the memorised component, thus it will trigger unmount of the memorised component. Therefore nothing can be memorised.

the solution is using css to hide it instead of not render it for my case

user192344
  • 1,274
  • 6
  • 22
  • 36