Get Call Depth Inside React Component

I’m trying to make a scene graph in React that supports nesting components. Something along the lines of:

<SceneNode>
  <SceneNode>
    <Thing/>
  </SceneNode>
  <SceneNode>
    <Thing/>
  </SceneNode>
</SceneNode>

When a SceneNode is mounted I need a way for it to know at what “depth” it is. Is there a way within a component to access that information? e.g.:

function SceneNode({children}:{children:ReactNode}) {
  const depth = useCallDepth(); // <- some magic function that lets me know the level of nesting for this node
  return <div>{children}</div>
}

NOTE: I’ve tried the following:

  • Context: Can’t get it to work without having each node create its own context but since context is referenced statically in React I can’t access the dynamically created parent contexts from children.
  • Refs: The nesting of components should be reflected in the DOM elements they produce, but I can’t figure out how to determine what the associated component is for a given DOM element – i.e. is this div a SceneNode or just a random div? (I suppose I could encode it in an attribute or id, but I was hoping for something a little cleaner and less invasive)
  • Manual: I can manually specify which nodes are parents (e.g. <SceneNode parent={true}/> but that’s pretty error prone.

Answer

It is possible to use context for this: Demo