Skip to content

React 18 let's make ref.currant to be reactive value #21903

@MaxmaxmaximusAWS

Description

@MaxmaxmaximusAWS

Let's add this hook as part of the core. Since this is a common need, many people often ask the question "Why does useEffect not sense ref.current changes?"

// approximate implementation
const useReactiveRef = (defaultValue) => {
  const [current, ref] = useState(defaultValue)
  ref.current = current
  return ref
}

Usage example:

const Component = () => {
  const ref = React.useReactiveRef()

  useEffect(() => {
    // ref.current now is reactive
    console.log(ref.current)
  }, [ref.current])

  return <div ref={ref}></div>
}

Metadata

Metadata

Assignees

No one assigned

    Labels

    React 18Bug reports, questions, and general feedback about React 18Type: Discussion

    Type

    No type

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions