Reader small image

You're reading from  Full-Stack Flask and React

Product typeBook
Published inOct 2023
Reading LevelIntermediate
PublisherPackt
ISBN-139781803248448
Edition1st Edition
Right arrow
Author (1)
Olatunde Adedeji
Olatunde Adedeji
author image
Olatunde Adedeji

Olatunde Adedeji is a seasoned web developer with over 15 years of experience in developing dynamic and detail-oriented enterprise web applications. Along with his extensive experience in developing, maintaining and supporting mobile, web and enterprise applications in Python, Go and JavaScript, Olatunde has consistently delivered excellent services, as team lead, team member or in consultancy capacity. Olatunde is proficient in application design and solution blueprinting; including mastery of application development tools such as: Flask, Django, Gin, React, and NodeJS. When not weaving the web and playing chess, Olatunde spends time with his wife, Adedoyin and two daughters, Mitchelle and Mabel.
Read more about Olatunde Adedeji

Right arrow

Managing State with React Hooks

Chapter 2, Getting Started with React, was a great way to kick off React frontend development. By now, you should be familiar with project directory structures and a few other concepts in React. In this chapter, we will take your understanding of React’s core concepts further.

Why does this matter? Simple. You can’t be the shining light you intend to be with React development without getting a grounding in the React core features and how we use them. This chapter focuses on managing state with React Hooks.

State in React is the medium through which we add interactivity to the user interface. Before React v16.8, developing class components was the only way you could add state and state transitions to your components.

Functional components were stateless; they were only able to display JavaScript XML (JSX) elements, that is, presentational components only. But with the Hooks API, you can add state and state transitions to your functional...

Technical requirements

The complete code for this chapter is available on GitHub at: https://github.com/PacktPublishing/Full-Stack-Flask-and-React/tree/main/Chapter03.

Due to page count constraints, the code blocks have been snipped. Please refer to GitHub for the full source code.

What is a Hook in React?

A hook is a special function provided by React that lets you use React core features—state and component lifecycle methods—within a function component. While state is an in-built object in React that adds interactivity and dynamic mechanism to components, the lifecycle tracks the phases components go through, from their initialization to their eventual demise (when a user navigates away or exits from an application UI).

There are three major cyclic phases React components go through, as explained in Chapter 2, Getting Started with React: mounting, updating, and unmounting. Each of these phases has what we call lifecycle methods that can be used during the rendering of React components.

We observed the presence of certain methods, such as componentWillMount(), componentDidMount(), componentWillUpdate(), and componentDidUpdate(), during the class component’s lifecycle. React hooks are used to make function components stateful without...

Why use Hooks in React?

In the history of React, Hooks represented a significant shift in how we approach stateful components and manage side effects. Prior to Hooks, writing or refactoring class components was the primary method to enable components to exhibit interactivity and handle other side effects. Components serve as the building blocks of React applications’ UIs, and creating interactive interfaces necessitated the use of class components.

However, for beginners, the class syntax and structure can be challenging to understand. Sophie Alpert, former manager of the React team at Facebook, in her keynote (React Today and Tomorrow) at the 2018 React Conference, said:

“I claim classes are hard for humans…but it’s not just humans, I claim the classes are also hard for machines”

– Sophie Alpert (https://bit.ly/37MQjBD)

The use of this and bind in class components adds to the list of confusion. While JavaScript offers both the...

Using useState to develop stateful components

The useState Hook allows you to manage state in React applications. Function components rely on the useState Hook to add state variables to them. State is an object in React that can hold data information for use in React components. When you make a change to existing data, that change is stored as a state.

This is how it works: you pass an initial state property to useState(), which then returns a variable with the current state value and a function to update this value. The following is the syntax of the useState Hook:

const [state, stateUpdater] = useState(initialState);

Let’s see a simplistic use case of how useState works:

import React, {useState} from 'react';const App = () => {
  const [count, setCount] = useState(0);
  const handleIncrementByTen = () => {
    setCount(count + 10);
  };
  const handleDecrementByTen = () => {
 &...

Using useEffect to create side effects

The useEffect Hook allows you to fetch data from external sources, update the DOM tree, and set up a data subscription. These operations are called side effects. In the class component, you have what we call lifecycle methods that can execute operations based on the phase of the component-rendering process. useEffect accepts two arguments: a function and an optional dependency.

It is important to note that useEffect does the work of the old componentDidMount, componentDidUpdate, and componentWillUnmount in one place. Using the useEffect Hook shortens the amount of code you have to write in a function component to achieve the same side effects.

The following is the syntax for the useEffects Hook:

- useEffect(<function>, <dependency>)useEffect(() => {
  // This callback function implementation is either to
     update DOM, fetch data from external sources, or to
    ...

Using useContext to manage global state in React applications

The useContext Hook is used to share application state data across the component tree without having to pass props down explicitly at every component level. To put it simply, useContext is a way to manage React applications’ global state. Remember, we used the useState Hook to manage local state in the Using useState to develop stateful components section.

However, as React project requirements expand in scope, it will be ineffective to use the useState Hook alone in passing state data in deeply nested components. The following is the syntax for the useContext Hook:

const Context = useContext(initialValue);

Briefly, we will discuss props drilling to understand the challenges it poses. Afterward, we’ll delve into the implementation of the context API, which addresses these issues.

Understanding props drilling

Let’s examine how you might pass data as props down a component hierarchy without...

Using useRef to directly access DOM elements and persist state values

The useRef Hook allows you to access DOM elements directly in React and is used to persist state values across re-renders. React, as a powerful library for UI, has a lot of novel concepts (virtual DOM design patterns, event handling, attribute manipulation) we can use to access and manipulate DOM elements without the use of traditional DOM methods.

This declarative approach to DOM is one of the reasons React is so popular. However, with useRef, we can directly access DOM elements and freely manipulate them without consequence. The team at React felt that with useRef, developers’ present and future cravings for direct DOM access might be met despite the React abstraction on top of the DOM.

There are two core uses of useRef:

  • Accessing DOM elements directly
  • Persisting state values that do not trigger the re-rendering of React components when updated

If you are interested in how many times...

Using useReducer for state management

The useReducer hook is a state management hook in a React application. It is quite a bit more robust than the useState hook we discussed earlier in this chapter as it separates the state management logic in the function component from the component-rendering logic.

The useState hook encapsulates the state management function with component rendering logic, which may become complex to handle in a large React project with the need for complex state management. The following is the syntax for useReducer:

`const [state, dispatch] = useReducer(reducer, initialState)

The useReducer hook accepts two arguments – the reducer, which is a function, and the initial application state. The Hook then returns two array values – the current state and the Dispatch function.

Basically, we need to understand these core concepts in useReducer:

  • State: This refers to mutable data that can be changed over time. State doesn’t have...

Using useMemo to improve performance

The useMemo Hook is part of the core APIs in React geared toward improving the performance of React applications. It uses a technique known in software development as memoization.

This is an optimization technique used to enhance the performance of software by keeping in memory the results of resource-intensive computation function calls and sending back the cached output when the same inputs are used subsequently. So, why is useMemo important in React application development? useMemo solves two performance problems for a React developer.

Prevents unnecessary component re-rendering

It memoizes the return value of a function for computations that consume a lot of resources by sending back a cached function result upon subsequent requests without a state update.

Let’s dive into a use case for useMemo to better understand how it can be used in React. This snippet shows how a component re-renders on every character search. With a...

Using useCallback to avoid re-rendering functions

In React function components, there is an additional optimization Hook called useCallback. It shares functionality with useMemo, with a slight difference in output behavior in terms of what is returned. In useCallback, a memoized function is returned, while useMemo returns memoized returned values of the function.

Like useMemo, useCallback is invoked when one of its dependencies is updated inside the function component. This ensures that the functional components are not necessarily re-rendered constantly. There are key highlights for useCallback:

  • A memoized callback function is returned in useCallback. This improves the performance of the React application based on memoization techniques.
  • The change in the dependencies of the useCallback Hook determines whether it will update or not.

Right now, let’s dive into a simple use case of useCallback for deeper understanding.

The following snippet displays a...

Using custom Hooks for code reusability

We have extensively discussed some of the in-built Hooks in React. Hooks have been part of the core React library since v16.8, which allows React components to exhibit statefulness without a class-based approach. Hooks such as useState, useEffect, UseMemo, useRef, useContext, and useCallback are specific functions to manage state, share stateful logic, and allow other interactions with React core APIs.

Now let’s understand what a custom Hook is and the benefits we can get from using them.

Custom Hooks are normal JavaScript functions whose name starts with use and that usually invoke one or more in-built React Hooks. For instance, custom Hooks could be named anything as long as it starts with use, for instance, useCustomHook, useFetchSpeakers, or useUpdateDatabase. Conventionally, there must be use in front of your custom Hook name.

So why should you want to build your own custom Hooks? Let’s examine some of the reasons...

Summary

In this chapter, we have been able to understand Hooks as a new mind shift in how we add statefulness to components in React. Prior to Hooks, only class components could offer us stateful functionalities. With React 16.8, we are now able to develop stateful functional components in React applications that are more elegant and concise.

The learning curve is easy as we can leverage our understanding of regular JavaScript functions and develop function components to power user interfaces for our web applications. With Hooks in React, user and developer experiences have been greatly improved.

In the next chapter, we will focus extensively on how we can leverage React APIs to fetch data from external sources into our web applications. Most of the applications we use today rely heavily on external data. Undoubtedly, React shines well in this domain.

lock icon
The rest of the chapter is locked
You have been reading a chapter from
Full-Stack Flask and React
Published in: Oct 2023Publisher: PacktISBN-13: 9781803248448
Register for a free Packt account to unlock a world of extra content!
A free Packt account unlocks extra newsletters, articles, discounted offers, and much more. Start advancing your knowledge today.
undefined
Unlock this book and the full library FREE for 7 days
Get unlimited access to 7000+ expert-authored eBooks and videos courses covering every tech area you can think of
Renews at $15.99/month. Cancel anytime

Author (1)

author image
Olatunde Adedeji

Olatunde Adedeji is a seasoned web developer with over 15 years of experience in developing dynamic and detail-oriented enterprise web applications. Along with his extensive experience in developing, maintaining and supporting mobile, web and enterprise applications in Python, Go and JavaScript, Olatunde has consistently delivered excellent services, as team lead, team member or in consultancy capacity. Olatunde is proficient in application design and solution blueprinting; including mastery of application development tools such as: Flask, Django, Gin, React, and NodeJS. When not weaving the web and playing chess, Olatunde spends time with his wife, Adedoyin and two daughters, Mitchelle and Mabel.
Read more about Olatunde Adedeji