Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

How can I measure a DOM node is a bad example #2556

Closed
ehaynes99 opened this issue Nov 12, 2019 · 2 comments
Closed

How can I measure a DOM node is a bad example #2556

ehaynes99 opened this issue Nov 12, 2019 · 2 comments

Comments

@ehaynes99
Copy link

ehaynes99 commented Nov 12, 2019

https://reactjs.org/docs/hooks-faq.html#how-can-i-measure-a-dom-node

This is a bad example for callback refs. The callback only gets called if:

  • The <input> element changes
  • The ref callback changes (never in this example)

It does NOT get called if the dom node is resized. Example:

function MeasureExample() {
  const [width, setWidth] = useState(0)
  const [divWidth, setDivWidth] = useState(200)
  const toggleWidth = () => {
    setDivWidth(w => (w === 100 ? 200 : 100))
  }

  const measuredRef = useCallback((node) => {
    if (node !== null) {
      setWidth(node.getBoundingClientRect().width)
    }
  }, [])

  return (
    <div style={{ maxWidth: `${divWidth}px` }}>
      <h1 style={{ width: '100%' }} ref={measuredRef}>Hello, world</h1>
      <h2>The above header is {Math.round(width)}px wide</h2>
      <button onClick={toggleWidth}>Change Width</button>
    </div>
  )
}

Measuring in real time would need useEffect to run on every render reading the value of a traditional ref. Is there some other example that would make more sense to demonstrate callback refs?

@Izhaki
Copy link

Izhaki commented Nov 15, 2019

To give a contrasting view, I always did one-offs measurements with useEffect and the example above was an epiphany for me.

But I agree the docs should state explicitly that the callback will only be called on mount/unmount.

@sophiebits
Copy link
Member

I'll amend the example to be clear about its limitations.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

No branches or pull requests

3 participants