14

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):

  1. To pass ref instead of ref.current. But then in use cases, I'll be forced to use something like contextRef.current instead of contextNode.

  2. 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?

CodeSandbox

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
);
sergdenisov
  • 8,327
  • 9
  • 48
  • 63

2 Answers2

3

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>
    );
};
Alvaro
  • 9,247
  • 8
  • 49
  • 76
  • 2
    `ref.current` will still be `null` in first render. – Dupocas Aug 20 '19 at 12:14
  • @Dupocas it will, let me update the answer with some proposal for that. – Alvaro Aug 20 '19 at 12:15
  • In the first variant, we also need to use state to rerender, I wrote about it. In the second variant, I don't want to get the app node. – sergdenisov Aug 20 '19 at 12:24
  • @SergeyDenisov Could you elaborate on what you mean with you don't want the node? I thought that is why you were passing the ref. – Alvaro Aug 20 '19 at 12:27
  • It's an example, in the real case I need a node from another component, not an app component. – sergdenisov Aug 20 '19 at 12:29
  • @SergeyDenisov Sorry then, I might be misreading the question. The second proposal is to set the initial value you want to pass using plain JavaScript, if you need the correct value in the first render. – Alvaro Aug 20 '19 at 12:31
  • Seems like not the best way in React. – sergdenisov Aug 20 '19 at 12:34
3

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.

Vencovsky
  • 28,550
  • 17
  • 109
  • 176
  • I wrote that I thought about the first variant, thanks. – sergdenisov Aug 20 '19 at 12:22
  • @SergeyDenisov this question looks like `primarily opinion-based`, but answering your question, `What is the correct (best?) way to do it?` I would say the first variant. – Vencovsky Aug 20 '19 at 12:24