Book Image

The React Workshop

By : Brandon Richey, Ryan Yu, Endre Vegh, Theofanis Despoudis, Anton Punith, Florian Sloot
5 (1)
Book Image

The React Workshop

5 (1)
By: Brandon Richey, Ryan Yu, Endre Vegh, Theofanis Despoudis, Anton Punith, Florian Sloot

Overview of this book

Are you interested in how React takes command of the view layer for web and mobile apps and changes the data of large web applications without needing to reload the page? This workshop will help you learn how and show you how to develop and enhance web apps using the features of the React framework with interesting examples and exercises. The workshop starts by demonstrating how to create your first React project. You’ll tap into React’s popular feature JSX to develop templates and use DOM events to make your project interactive. Next, you’ll focus on the lifecycle of the React component and understand how components are created, mounted, unmounted, and destroyed. Later, you’ll create and customize components to understand the data flow in React and how props and state communicate between components. You’ll also use Formik to create forms in React to explore the concept of controlled and uncontrolled components and even play with React Router to navigate between React components. The chapters that follow will help you build an interesting image-search app to fetch data from the outside world and populate the data to the React app. Finally, you’ll understand what ref API is and how it is used to manipulate DOM in an imperative way. By the end of this React book, you’ll have the skills you need to set up and create web apps using React.
Table of Contents (20 chapters)
Preface

More Refactoring with Custom Hook

In the previous sections, we learned how to use hooks to fetch data in a function component. We also discussed how to avoid the infinite loop by specifying the second argument in useEffect.

In this section, we will learn how to further refactor the previous code by using a custom hook. While developing React applications, it is always a good idea to reuse code in one place and share it across different components.

As we discussed in the previous chapter, and also specified in the React documentation (https://packt.live/3cwLUjN), Building your own hooks lets you extract component logic into reusable functions, which means hooks allow us to easily share and reuse code.

Let's recap how to create the custom hook. To create a custom hook, we first create a new file. The filename convention is to start with use, followed by the hook name—for example, useResponse.js.

Inside the hook file, we need to import necessary hooks, such as...