How correctly pass a node from a ref to a context? How correctly pass a node from a ref to a context? reactjs reactjs

How correctly pass a node from a ref to a context?


Instead of passing the ref which doesn't trigger a render when changed, use a state that holds the ref. This way you can change the Context from a child if needed, and at the same time you get the value updated correctly.

const App = ({ children }) => {    const ref = useRef(null);    const [ref_state, setRefState] = useState(null);    useEffect(() => {        if (!ref.current) {            return;        }        setRefState(ref.current)    }, []);    return (        <div ref={ref_state}>            <Context.Provider value={ref.current}>{children}</Context.Provider>        </div>    );};

If you need the initial render to point to the element, you could (in a non-optimal way) set the initial value to the HTML element:

const App = ({ children }) => {    const ref = useRef(document.querySelector("#app"));    return (        <div id="app" ref={ref}>            <Context.Provider value={ref.current}>{children}</Context.Provider>        </div>    );};


I didn't know about that, but passing ref.current doesn't work in the first render, but if you only pass ref, it will work in the first render.

Where is the working codesandbox.

I don't think that this

then is use cases I'll be forced to use something like contextRef.current instead of contextNode.

Will be a issue, it will be good, because when using it, you will know that what you are getting is a ref.

Also,

Do this

Use a state (something like firstRender) to rerender a component after getting a ref.current. This seems not optimal.

Only for not using ref.current, doesn't look like a good practice.