Learning about useEffect today. Gosh React is hard work!
The thing I want to remember is how the second parameter (the dependencies array) works.
There are three options for this:
No dependencies array – this causes the effect to run on initial render and EVERY re-render
useEffect(
() => {
// Some side effect
}
// No second param - effect runs on EVERY render.
)
Empty dependencies array – this causes the effect to only run on initial render – it won’t run on re-renders
useEffect(
() => {
// Some side effect
},
[] // Empty second param - effect runs on INITIAL RENDER ONLY.
)
Non-empty dependencies array – this causes the effect to run a) on initial render b) on any re-render when the state values in the array have changed
[name, setName] = useState({ firstName: 'Ross', lastname: 'Wintle' })
useEffect(
() => {
// Some side effect
},
[name] // Non-empty second param - effect runs on initial render and when name has changed.
)
The thing I really don’t get is how the examples used in the Scrimba course cause this double initial render. They use the useEffect hook to run an API query to fetch data after the initial render. This will then trigger a re-render.
So I’m hoping that a future lesson shows me how to load the data before the initial render. Maybe this would slow down a client-side page load, but it seems like exactly what I would want to do if I was server-side rendering.
UPDATE: It looks like this is exactly what frameworks like Next.js help with! So I’ll be digging into that soon.