An Introduction to React Hooks (JavaScript) — Part 2
This article is a sequel to the previous An Introduction to React Hooks (Javascript) — Part 1. If you haven’t read it yet, please do :). In this article I will be covering:
useReducer
useLayoutEffect
Usage: useReducer
The useReducer
hook enables you to use reducers to control state in your React application.
What is a reducer?
A reducer is a function that enables you to provide the current state of a component and return the next, updated state. It has two parameters: state and action. An action always has a .type
property, which is a string, and an optional .payload
property to provide an external value. To run reducers, there is a dispatch
function, wherein you input the action type (and payload).
This is a common syntax:
In case you are a TypeScript user, reducers are some of the go-to things in your React application because of excellent type intelliscence. Using typescript:
In a separate article, I’ll show you all the tips and tricks you can use to build and use reducers in your applications (React, or non-React).
Back to React
This is how you would use it in an application. The action types make it much easier to determine the action that is being performed, making them very helpful when managing complex states.
It’s that simple!
Usage: useLayoutEffect
Firstly: this is hardly used. Only helpful to measure the properties of page elements. The hook runs synchronously, unlike useEffect
, which could affect page painting. Usage is exactly like useEffect
. (Refer to the previous article to learn its usage)
Conclusion
That’s it for today! Stay tuned for part 3, where I will discuss React context and the useContext
hook, and how to build your custom hook. Thanks for reading!