How does React links dependencies in `useEffect` hook to state?

felps321 :

I imagine very good how React's "useState" hook works. State - is a list of values mapped to certain component, and theres also index of useState call, which is requesting state value index. When React renderer encouters component, it writes it into outer reference, to which useState have access, so it returns state value by useState call index, from "current" component's state list. But I have no idea, how does React identify and link dependencies in "useEffect" to actual state which obviously is plain values like numbers and strings. How is that done?

import React from 'react'

function Component() {
  const [plainString, setPlainString] = React.useState('Hello')
  const [anotherPlainString, setAnotherPlainString] = React.useState('Good bye')

  // update `plainString` after mount
  React.useEffect(() => {
    setPlainString('Updated Hello')
  }, [])

  // callback get triggered after `plainString` update!
  // but how it links dependency to state if its just 'Hello' string?
  React.useEffect(
    () => {
      console.log(plainString) // "Updated Hello"
    },
    [plainString]
  )

  return <h1>plainString</h1>
}
azium :

It's simply whether the values in the dependency array change, they don't even have to be stateful.

useEffect(() => {

}, dependencyArray) // React loops over these values to check for changes

You can test this pretty easily with random numbers

dependencyArray = [Math.random(), Math.random(), Math.random()]

Which will very likely create an array with different values on rerenders.

If the first time it gets [0.1, 0.2, 0.3] and the next time it gets [0.1, 0.2, 0] It will trigger the effect again because the values in the array are not the same.

Guess you like

Origin http://43.154.161.224:23101/article/api/json?id=29759&siteId=1