Playing with React Hooks
- Published on
- Related tags
This article was written the week following React Conf 2018, after the team announced their proposal for React Hooks.
This article was originally posted on Medium back in 2019, and I've ported it here for historical purposes/nostalgia 😄 Read on medium.com.
Last week at React Conf 2018 the team announced a new proposal for React Hooks, a new API that allows you to use state and other features more directly without the need for classes. There are no breaking changes and it's completely opt-in, so if you're not hooked just yet (heh) you don't have to use them and can continue using classes, no problems. Pretty exciting stuff!
It's currently only in the proposal stage but if you're like me you love playing around with new features, so you can start integrating them right now with the React v16.7.0-alpha.0 release.
One hook in particular has me pretty excited, and that is useReducer
. It offers Redux-like functionality without needing to bring in a separate state management package 😮 Really cool!
With useReducer
we get the current state along with a matching dispatch method. This is particularly useful with the new useContext
hook, as I discovered while playing around with the two together over the weekend. I created a simple little app that allows you to update the width, height and background of a square.
Inside Context.js
we initialize the context and create the reducer, and also create the provider component (AppContextProvider
) which wraps around the Controls
and Square
components (they are siblings). This means when the context is updated via the Controls component, Square is able to get the updates without having to pass any props down. Pretty cool 😃
Let's go over how all this works. Starting in Context.js:
You don't have to create the Provider in a separate component like above, but I like doing it that way because it keeps things very clean in App.js
. Personal preference 🤷
The resulting App.js
imports the Provider which then wraps around the components, enabling them to subscribe to the context changes.
In the Controls
component, we then have to import the context for use with useContext
. From that, we can pull off the state and dispatch.
And then all we have to do in Square
component is pull the state off from the context and pass it down as props for styling (I'm using styled-components). Easy peasy!
After some inevitable initial confusion, I feel like ultimately hooks are pretty intuitive to me. I'm excited to see where things go and welcome the new addition to React. Will definitely be using them down the line when they are officially released.
Thanks for reading, and if you want to dive deeper into the above, the code is available on Github 👍