Implement 'useTheme' using Hooks API
See original GitHub issueHey there! 👋
I was wondering if there are plans on implementing Hooks API for specific parts regarding context providers? This would help us to use something like useTheme()
outside of context of styled components, where we’re currently using either withTheme
HOC, or a render props pattern.
The implementation could probably be as simple as following:
const useTheme = (...path) => path.join(".").split(".")
.reduce((a, c) => (a && a[c] ? a[c] : null), useContext(ThemeContext));
and it would allow us to do something like:
<Component background={useTheme('colors.blue')} />
I guess this has already been thought of, but since I couldn’t find any issue related to it, I wanted to get your opinion on it.
I’d be more than happy to do a PR including something like this, maybe under something such as styled-components/hooks
for now, until 16.8 (hopefully 🤓).
Issue Analytics
- State:
- Created 5 years ago
- Reactions:27
- Comments:10 (4 by maintainers)
Top Results From Across the Web
useTheme React Hook - useHooks
This hook makes it easy to dynamically change the appearance of your app using CSS variables. You simply pass in an object containing...
Read more >Hooks API Reference - React
They let you use state and other React features without writing a class. This page describes the APIs for the built-in Hooks in...
Read more >Toggle theme using React Hooks - Vimal Selvam
To create a context object, we should use React's createContext method and pass the default value to it (i.e., initial state). const ThemeContext...
Read more >useTheme - React Navigation
The useTheme hook lets us access the currently active theme. You can use it in your own components to have them respond to...
Read more >React Hooks - changing themes through useContext - YouTube
In a typical React application, data is passed top-down (parent to child) ... Let's see how to use the Context API through useContext...
Read more >Top Related Medium Post
No results found
Top Related StackOverflow Question
No results found
Troubleshoot Live Code
Lightrun enables developers to add logs, metrics and snapshots to live code - no restarts or redeploys required.
Start FreeTop Related Reddit Thread
No results found
Top Related Hackernoon Post
No results found
Top Related Tweet
No results found
Top Related Dev.to Post
No results found
Top Related Hashnode Post
No results found
Top GitHub Comments
For anyone looking for a dead simple hook while we wait for something official:
useTheme
was added in https://github.com/styled-components/styled-components/pull/2765 by @semoal 🎉 Once a new version is released, your React components will be able to do this:This solution is a bit better than
useTheme('colors.blue')
, which was originally proposed in this issue. Reasons are type-safety and performance.