Building The Same Application With and Without React Hooks, Part 1
With the release of React Hooks, many people may be wondering, what is the benefit of hooks anyway, or even what are hooks?
What are Hooks
Hooks are functions that allow you to “hook into” React state and lifecycle methods from within function components. An example of a “hook” is
useState is a hook that allows us to utilize stateful behavior from within a function component. We'll cover an example use of this built in hook in the next section.
Hooks allow us to make all of our components function components. This does not mean that class components no longer work, they can coexist alongside function components and hooks.
Since hooks allow for stateful logic within a function component, we remove the necessity of managing and binding the value of
this across a component. This not only makes component code easier to read, but also to write.
Lets take a look at a simple component written in a standard class based manner:
And now lets compare that to the same component written with two simple hooks built in to React:
The second component still manages to use stateful logic, it still fetches when the component mounts, but also manages to not use a single
this anywhere. This implementation of hooks is at the most basic level with no custom hooks or reducers and yet the code is already much easier to follow and much easier to write.
We can take this a step further and take our stateful logic and collocate it in a reducer hook using
We can define a custom reducer for our stateful logic and collocate in order to make the logic reusable.
We can then import this custom reducer function using the
useReducer hook in react.
By importing our stateful logic from this reducer function we’ve created, we can reuse our logic if we need to in other components. This will come in handy once we incorporate other hooks such as
useContext into our application.
We can go even further and make more of our code reusable by creating a custom hook. We’ll call it
We have now relocated not only our dispatch, but also all of our stateful methods that invoke our dispatch into our custom hook. Now our slim App component looks like:
You can see from the snippet above that our App component has become significantly smaller and easier to read. There are no instances of
this anywhere to be found in our code and our logic is now reusable. There are however still some things we can improve upon.
In this example, we are still using our dispatch as part of our fetch. We can get around this if we wanted to create a synchronous fetch function. Along with this, we are still passing down our stateful logic to child components as props. There is a hook built in to react to help us solve this issue, called
These improvements to this application will be the focus of the next part of this blog post, so stay tuned!