Effect Cleanup
Esmė tokia, kad nors ir komponentas bus unmounted, gali likti atmintis užimta. Todėl reikia išvalyti efektorius.
useEffect (() => { function handleEvent() { // some-event happened! } window.addEventListener('some-event', handleEvent) return () => { window.removeEventListener('some-event', handleEvent) } }, [])
Kaip pasireiškia atminties nutekėjimas ir kaip fixint.
Sukuriamas ReactJs komponentas su useEffect ir ten kazkokia funcija. Uždarius komponenta atmintyje lieka ryšiai (ref, async uzkrauta atmintis ir t.t.)
const dogChecked words. includes ('dog') const cat Checked = words. includes ('cat') const caterpillar Checked = words. includes ('caterpillar') useEffect (() => { // you can use this to test whether your cleanup is working const hugeData = new Array(1_000_000).fill(new Array(1_000_000).fill('....') // extract your event handler here into a function called updateQuery window.addEventListener('popstate', () => { // you can use this to test whether your cleanup is freeing up memory // console.log(hugeData) console.log('popstate event listener called') setQuery(getQueryParam()) }) // return a function which removes the popstate https://developer.mozilla.org/en-US/docs/Web/ }, [])
mount -> unmount -> mount -> unmount komponenta augs naudojama atmintis (memmory leak)
Sprendimas:
useEffect (() => { const hugeData = new Array(1_000_000).fill( new Array(1_000_000).fill('ON'), ) const handlePopState = () => { console.log('popstate event listener called') setQuery(getQueryParam()) } window.addEventListener('popstate', handlePopState) return () => { window.removeEventListener('popstate', handlePopState) } ], [])
const handlePopState- iškeltas į nauja kintamaji, kad linkus tuos pacius perduoti tiek add tiek remove event listener- kas ivyks event handler isliks net unmount komponantą (
const handlePopState = () => {) - rezultate unmount komponentui suveiks cleanup return fn, ir garbage collector isvalis atmintį