reactjsdepthscenegraph

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:


Solution

  • It is possible to use context for this: Demo