I'm trying to pass a node from a ref to a context. But because I have no re-render after the first render, the passed node is null. I thought about two variants (but I think they aren't the best):
- To pass - refinstead of- ref.current. But then in use cases, I'll be forced to use something like- contextRef.currentinstead of- contextNode.
- Use a state (something like - firstRender) to re-render a component after getting a- ref.current. This seems not optimal.
What is a correct (the best?) way to do it?
import React, { createContext, createRef, useContext, useEffect } from "react";
import ReactDOM from "react-dom";
const Context = createContext(null);
const App = ({ children }) => {
  const ref = createRef();
  return (
    <div ref={ref}>
      <Context.Provider value={ref.current}>{children}</Context.Provider>
    </div>
  );
};
const Child = () => {
  const contextNode = useContext(Context);
  useEffect(() => {
    console.log(contextNode);
  });
  return <div />;
};
const rootElement = document.getElementById("root");
ReactDOM.render(
  <App>
    <Child />
  </App>,
  rootElement
);
 
     
    