Master useState & useEffect React Hooks API

Daryll Wong
codeburst
Published in
6 min readJul 31, 2020

--

An explanation of the common ways to use useState & useEffect Hooks API

cover photo of react useState & useEffect

As we move towards creating more functional components over class components for cleaner code, we will be using the React Hooks APIs more often. The first few React Hooks that we will use are: useState and useEffect. Hence, it is important that we understand and master them fully, and implement them in our react apps correctly.

In this article, I will try to give easy-to-understand explanations of these hooks and illustrate them with practical examples in code sandbox. At the end, I will also give common examples of using useState to update/manipulate state values.

Understanding useState Hook

In React, states store a component’s data that is dynamic. React picks up changes to the state to re-render the UI where-ever necessary. The simplest example of this would be a counter button page with a state that stores the number of counts that is displayed on the UI, and this changes dynamically whenever the count updates.

As mentioned, functional components are generally preferred over class components as the code is cleaner, easier to debug, etc. Let’s quickly compare how we would store and update states with both class and functional components.

Using Class Component

For Class Components, the state is initialised in the class with this.state={...}and to modify the state, this.setState({...}) is used.

Note how I have to create rather lengthy handler functions for buttons to increase the counts.

Let’s compare the exact same app written in as a Functional Component.

Using Functional Component

To store states in a functional component, we have to use the useState Hooks API which gives us a very convenient way to store and update the states.

--

--