In my recent “Custom Properties as State” post, one of the things I mentioned was that theoretically, UI libraries, like React and Vue, could automatically map the state they manage over to CSS Custom Properties so we could use that state right there if we wanted.
Someone should make a
useStateWithCustomProperties
hook or something to do that. #freeidea
Andrew Bloyce took me up on that idea.
It works just like I had hoped. The hook returns a component that is the Custom Property “boundary” and any state you pass it is mapped to those custom properties. Basic demo:
This is clever and useful already, but I’m tellin’ ya, this will be extremely useful should the concept of higher level custom properties land. The idea is that you could flip one custom property and have a whole block of styling change, which is is what we already enjoy with media queries and you know how useful those are.
Hello, i’m sorry but this lib should not be used as it is, you should not create component types during render, the way this is architected will lead to you not being able to hold any internal state from that component down. If anything re-renders it will destroy the whole component tree underneath it and create a new one cause if component types change during render React will destroy the whole component tree.
Would be good to have a non-react / vanilla js example of how this works.
The point is mapping the custom properties from a system that is designed to be managing state anyway. In Vanilla JavaScript, you can update a custom property like this: