2

The example below will throw a warning that someState should be included in the dependency array of the useEffect, however I do not wish for changes to someState to trigger the useEffect to run.

So, how do I make sure that the function runs on updates to someTrigger while running with an updated version of someState?

import React, { useState, useEffect } from 'react'

function someFunction() {
  const [someTrigger, setSomeTrigger] = useState(null)
  const [someState, setSomeState] = useState({})

  useEffect(() => {
    async function postSomething() {
      const response = await fetch('somePath',
         method: 'POST',
         body: JSON.stringify(someState),
      })
      ...
    } 
    postSomething()
  } [someTrigger])

  return <SomeComponent />
}
  • 1
    Couldn't you just add `someState` as dep? Since you're not changing it inside the effect this won't generate a loop – Dupocas Dec 10 '19 at 13:16
  • In this example, you're right, but in my actual use case I cannot. I need the trigger to be in control of the runtime. – Holger Thorup Dec 10 '19 at 13:28
  • What do you mean by that? Only trigger the effect when `someTrigger` changes? – Dupocas Dec 10 '19 at 13:28
  • 1
    But since `someState` is a piece of local state it is expected to change. And the effect should run again to keep synchronicity. If `someState` never changes you could declare it outside your component – Dupocas Dec 10 '19 at 13:30
  • Yes. I only want the effect to run when `someTrigger` changes, not when `someState` does. – Holger Thorup Dec 10 '19 at 13:31
  • But what if `someState` changes? What is the expected behavior for that? The effect should run only once? – Dupocas Dec 10 '19 at 13:32
  • Exactly. Is there any way I can keep its synchronicity, without running `postSomething()` on every update to `someState`. It shouldn't just run once, but every time `someTrigger` updates. – Holger Thorup Dec 10 '19 at 13:33
  • 1
    You could use https://stackoverflow.com/a/55854902/2295549, https://reactjs.org/docs/hooks-faq.html#is-it-safe-to-omit-functions-from-the-list-of-dependencies, https://overreacted.io/a-complete-guide-to-useeffect/ – Florian Motteau Dec 10 '19 at 13:36

1 Answers1

0

If you need to postSomething in response to some event, it is better to just call it the event handler directly, instead of going through an effect:

<SomeComponent onEvent={() => postSomething() } />

If for some reason that doesn't work for you and you need an effect, you can just ignore the warning.

vkurchatkin
  • 13,364
  • 2
  • 47
  • 55