How to useContext with custom renderers like react-three-fiber and react-konva
Libraries like react-three-fiber and react-konva are fantastic in that they allow React app developers to create 2D and 3D Canvas content while sticking with all that's great about React components. The difference of course, is that rather than manipulating the DOM, they are instead controlling Canvas elements. To achieve this, these libraries implement custom renderers, or reconcilers in React.
For the most part, these libraries work like any other React libraries, but they both suffer from a React issue that doesn't allow the
useContext hook inside the custom reconcilers:
In the above example, you can see that the
<Test> component, properly logs out MyContext value.
But when moved to be as a child of
<Canvas>, which is the react-three-fiber's renderer, we get this lovely error:
How do you fix this?
You can work around this by avoiding the use of
useContext altogether and pass the values you need into the children using props. But this isn't a great solution. The other option is to use a bridge context to proxy the values into a new Context that you can consume inside the renderer:
It's not the most elegant, but it does work.