pmndrs / its-fine

🐶🔥 A collection of escape hatches for React.
https://npmjs.com/its-fine
MIT License
1.05k stars 10 forks source link

feat: poc implementation #2

Closed CodyJasonBennett closed 2 years ago

CodyJasonBennett commented 2 years ago

Initial implementation with base react-internal methods for Fiber and container manipulation.

useFiber

Returns the current react-internal Fiber.

function Component() {
  const fiber = useFiber()

  React.useLayoutEffect(() => {
    console.log(fiber.type) // function Component
  }, [fiber])
}

useContainer

Returns the current react-reconciler Container.

function Component() {
  const container = useContainer()

  React.useLayoutEffect(() => {
    console.log(container.containerInfo.getState()) // Zustand store (e.g. R3F)
  }, [container])
}

useNearestChild

Returns the nearest react-reconciler child instance.

function Component() {
  const childRef = useNearestChild()

  React.useLayoutEffect(() => {
    console.log(childRef.current) // { type: 'primitive', props: {}, children: [] } (e.g. react-nil)
  }, [])

  return <primitive />
}

useNearestParent

Returns the nearest react-reconciler parent instance.

function Component() {
  const parentRef = useNearestParent()

  React.useLayoutEffect(() => {
    console.log(parentRef.current) // { type: 'primitive', props: {}, children: [] } (e.g. react-nil)
  }, [])

  return null
}

export default () => (
  <primitive>
    <Component />
  </primitive>
)

useContextBridge

Returns a ContextBridge of live context providers to pierce context across renderers.

function Canvas(props: { children: React.ReactNode }) {
  const Bridge = useContextBridge()
  render(<Bridge>{props.children}</Bridge>)
  return null
}

ReactDOM.createRoot(window.root).render(
  <Providers>
    <Canvas />
  </Providers>
)

traverseFiber

Traverses through a Fiber, return true to halt.

const ascending = true
const prevElement = traverseFiber(fiber, ascending, (node) => node.type === 'element')