Side-Effects

ReactJs have a lot iontegrations:

  • Browser APIs like local storage, geolocation, media devices
  • Integrations with third-party libraries like D3, Chart.js

Side-Effects yra kaip rezultatas iš integracijos, kuris keičia state

useEffect (() => { // your side-effect code here. // this is where you can interact with browser APIs for example doSomeThing() return function cleanup() { // if you need to clean up after your side-effect (like unsubscribe from on // event), you can do it here doSomeCleanup() } }, [ // this is where dependencies of your useEffect callback go // we'll talk about this in depth in a future exercise. // In this exercise, we'll just leave it as an empty array dep1, dep2, ])

doSomeThing() - kodas kuris vykdomas efekto metu return function cleanup() - unmount metu vykdomas kodas doSomeCleanup() - valome event listener [dep1,dep2] - callback vykdomas kei pasikeičia dependence

StrictMode useEffect vykdomas du kartus, kad butu galima pagauti bugą

Dar momentas, jeigu doSomeThing() vykdymo metu pakeis [dep1,dep2] priklausomybę. Pateksime į infinite loop. Jeigu perduodime aunc funkcija kai priklausomybe, galime patekti į infinite loop

Hook Flow

alt text

Run lazy initializers - stadija useState

Render (mount)

Renderinimo metu:

1 - render fazė kūriamas DOM

2 - React updates DOM - atnaujinamas DOM

3 - Browser paints screen - baigimas piešimas

Nuo 1 iki 3 - laikas kai pamatome vizualų vaizdą

Update

1 - React updates DOM - piešiami atnaujinimai

2 - Cleanup LayoutEffects

3 - Run LayoutEffects

4 - Browser paint screen

1 - 4 laiko tarpas tarp updeito ir kai pamatome pakeitimą.

Run effect

Run effects - paleidžia useEffects

Render - loaderiui užkrauti

Unmount

1 - Cleanup LayoutEffects

2 - Cleanup Effect - išvalome. Pvz web socket

Kiti

useEffect ir funkcijos doSomeTing šalia vienas kito, kad nebutu linku kurie gali pasikeitsi ir doSomeThing ves į nebeagzistuojantį linką.

Pvz fix loading (back mygtukas naršyklėj

Tikslas jeugu klientas paspaudžia back arba nect - pagauti ir atnaujinti query. Kadangi nėra dependence [] paleis pirmą kartą.

function getQueryParam() { const params = new URL SearchParams (window.location.search) return params.get('query') ?? '|' } function App() { const [query, setQuery] = useState(getQueryParam) const words = query.split(' ') const dogChecked = words.includes('dog) const catChecked = words.includes('cat') const caterpillarChecked = words.includes('Caterpillar') useEffect (() => { window.addEventListener('popstate', () => setQuery (getQueryParam) }, []) function handleCheck (tag: string, checked: boolean) {