- July, 2020
- Share It
Components are heart of React, and they can be either Function or Class components. Both have some additional features, such as state. State is fundamental feature of React and an attribute of each component. When state changes, component re-renders.
React 16.8 introduced something called hooks which allow us to use state and other features without having to use a class component. Everyone who has used React before knows that if you want to use state in your component you have to use class. That’s changing with hooks.
The list of built-in hooks is long and they are split into:
– Basic: useState, useEffect, useContext
– Additional: useReducer, useCallback, useMemo, useRef, useImperativeHandle, etc
There is even possibility of writing custom hooks. More about them you will find in the upcoming posts.
Stateful class component vs functional component
We can now have state within functional base component with useState hook. In the following example you will see how to replace class state with useState hook and how you benefit from using it.
Very basic thing such as storing one value in the state in class component is implemented as shown in the picture below:
In class component state is an object which can have multiple fields and is initialized in the constructor method. According to ES6 you must first invoke super before using this, so this part is also mandatory. Binding methods in the constructor is also needed.
By converting class to function component and using useState hook, implementation of the exactly same thing looks like this:
useState declares state variable year, so there is no need to access state object, nor to use constructor method. Simple change of year variable by calling function setYear() changes its value and triggers re-rendering of the component.
Using useState hook is easier to work with and make the code much cleaner and more readable.
There is much more to it
Seeing this basic example is probably not enough to realize how powerful hooks are.
They are used for solving much bigger problems, such as following:
– Decomposing huge components that are hard to refactor and test by creating reusable code
– Removing duplicated logic that is usually result of implementing lifecycle methods
– Solving “wrapper hell” which is created with using complex patterns like render props and higher-order components
There is a lot more about hooks that needs to be covered. True power of hooks you can see in some of next blog posts where it will be explained how to replace component’s lifecycle methods with useEffect hook.
Author: Selena Matijević, Software Engineer at enjoy.ing