Normally, with props, we can write
componentDidUpdate(oldProps) {
if (oldProps.foo !== this.props.foo) {
console.log('foo prop changed')
}
}
in order to detect prop changes.
But if we use React.createRef()
, how to we detect when a ref has changed to a new component or DOM element? The React docs don't really mention anything.
F.e.,
class Foo extends React.Component {
someRef = React.createRef()
componentDidUpdate(oldProps) {
const refChanged = /* What do we put here? */
if (refChanged) {
console.log('new ref value:', this.someRef.current)
}
}
render() {
// ...
}
}
Are we supposed to implement some sort of old-value thing ourselves?
F.e.,
class Foo extends React.Component {
someRef = React.createRef()
oldRef = {}
componentDidMount() {
this.oldRef.current = this.someRef.current
}
componentDidUpdate(oldProps) {
const refChanged = this.oldRef.current !== this.someRef.current
if (refChanged) {
console.log('new ref value:', this.someRef.current)
this.oldRef.current = this.someRef.current
}
}
render() {
// ...
}
}
Is that what we're supposed to do? I would've thought that React would've baked in some sort of easy feature for this.
useLayoutEffect
to make sure that the ref is not null. – MarmorealuseLayoutEffect
after React has updated DOM, and so any refs must have been changed at that point. Good tip. I think that's worthy of being its own answer! – Dietitian