Hacker News new | ask | show | jobs
by tekkk 2381 days ago
Your comment reminds me, I never found a perfect explanation what a negation inside the dependency array does. Does it simply negate the checked variable or just omits it from ever triggering eg useEffect? For example:

  const useClickOutside = (ref, onClickOutside, isActive) => {
    ...
    useEffect(() => {
      if (!isListening && isActive) {
        addHandlers(handler)
        setListening(true)
      } else if (isListening && !isActive) {
        removeHandlers(handler)
        setListening(false)
      }
      return () => {
        removeHandlers(handler)
      }
    }, [ref, !onClickOutside, isActive])
  }
I remember adding the negation here as the useEffect would fire needlessly (or wouldn't, can't remember), but wasn't entirely sure what it did. The whole hook is just for checking clicks outside an element.

Anyway, I agree with you that at times they can a bit too abstract for the fellow programmer. Without prior knowledge how hooks work it can be quite tedious to read (without proper documentation at least)

3 comments

In this case, onClickOutside was probably a function that you defined inline in your parent component, which would actually be a new thing on each render.

(Something like <Blabla onClickOutsite={() => doSomething()} />)

Since a function is an object, and objects get compared by reference, a new function that does the same thing is not equal to the old function. Thus, this is a change.

Negating it turns that into a boolean, which gets compared by value. false is the same as false, so no change. Any type coercion (e.g turning it into a string) would've worked.

In this case, there's nothing specific to React or hooks, just plain old JS comparison.

Negation just includes the opposite boolean value in the array. _If_ that value at that index happens to be different than the last time the component rendered, the effect will run again.
The negation is effectively just a cast to boolean in that situation. If the value changes from truthy to not-truthy or vice versa, then the effect will run again, otherwise it won't.

Based on the name, it seem like onClickOutside will always be a function, so always truthy, so it's effectively the same as just leaving it out of the dependency array.