Simplifying State Management in React Native - Aleksandra Desmurs-Linczewska - E-Book

Simplifying State Management in React Native E-Book

Aleksandra Desmurs-Linczewska

0,0
19,19 €

-100%
Sammeln Sie Punkte in unserem Gutscheinprogramm und kaufen Sie E-Books und Hörbücher mit bis zu 100% Rabatt.
Mehr erfahren.
Beschreibung

Managing state in a React Native app can be challenging as it is one of the most difficult concepts to grasp while learning React Native. This is because there are so many ways to do it, and because there is a lack of clear guidelines on what should be used and why.
Simplifying State Management in React Native is a comprehensive introduction for those who are new to creating robust React Native apps that will have you up to speed in no time. You’ll get to grips with the different state management strategies and libraries available. As you progress through the chapters, you’ll try out different solutions, as well as compare and choose which solution is perfectly suited to your future projects and personal preferences. Finally, you’ll create a social media clone app using all the concepts and examples that you’ve learned in this book.
By the end of this book, you’ll be able to take on existing projects that use various state management strategies and libraries, and confidently make decisions about state management.

Das E-Book können Sie in Legimi-Apps oder einer beliebigen App lesen, die das folgende Format unterstützen:

EPUB
MOBI

Seitenzahl: 246

Veröffentlichungsjahr: 2023

Bewertungen
0,0
0
0
0
0
0
Mehr Informationen
Mehr Informationen
Legimi prüft nicht, ob Rezensionen von Nutzern stammen, die den betreffenden Titel tatsächlich gekauft oder gelesen/gehört haben. Wir entfernen aber gefälschte Rezensionen.



Simplifying State Management in React Native

Master state management from hooks and context through to Redux, MobX, XState, Jotai and React Query

Aleksandra Desmurs-Linczewska

BIRMINGHAM—MUMBAI

Simplifying State Management in React Native

Copyright © 2023 Packt Publishing

All rights reserved. No part of this book may be reproduced, stored in a retrieval system, or transmitted in any form or by any means, without the prior written permission of the publisher, except in the case of brief quotations embedded in critical articles or reviews.

Every effort has been made in the preparation of this book to ensure the accuracy of the information presented. However, the information contained in this book is sold without warranty, either express or implied. Neither the author, nor Packt Publishing or its dealers and distributors, will be held liable for any damages caused or alleged to have been caused directly or indirectly by this book.

Packt Publishing has endeavored to provide trademark information about all of the companies and products mentioned in this book by the appropriate use of capitals. However, Packt Publishing cannot guarantee the accuracy of this information.

Group Product Manager: Rohit Rajkumar

Publishing Product Manager: Nitin Nainani

Senior Editor: Aamir Ahmed

Technical Editor: Joseph Aloocaran

Copy Editor: Safis Editing

Project Coordinator: Manthan Patel

Proofreader: Safis Editing

Indexer: Rekha Nair

Production Designer: Ponraj Dhandapani

Marketing Coordinator: Nivedita Pandey

First published: January 2023

Production reference: 2200223

Published by Packt Publishing Ltd.

Livery Place

35 Livery Street

Birmingham

B3 2PB, UK.

ISBN 978-1-80323-503-5

www.packtpub.com

To my entire family, for supporting me throughout the process of writing this book.

– Aleksandra Desmurs-Linczewska

Foreword

I met Aleksandra at a tech conference in Poland, and for as long as I’ve known her, she’s been a skilled, passionate and a driven Software Developer. I am now adding a fantastic educator to the list: her friendly tone and easy way of explaining things makes her technical writing great to comprehend and learn from.

State management is a must-have skill for almost every software application, mobile or otherwise. If your app has data, there’s state to manage. The huge number of open-source libraries out there handling just about anything you can think of is both a blessing and a curse: how in the world are you meant to choose what’s best? Sure, over time you’ll develop preferences, but even preferences should be reviewed frequently, in case something better suited has come around. Aleks’s book provides a wonderful overview of the most popular options available out there for state management in React Native today. Whether you’re new to React Native and looking to get the lay of the land, or an experienced developer syncing up with the latest industry trends, there is something valuable in here for you!

The book is divided into three parts: first, an introduction to React (Native), then an overview of state management, and finally an in-depth review of some of the more popular state management libraries today: Redux, MobX, XState, Jotai and React Query. Aleks also provides beautiful designs in Figma, and a GitHub repo with all the solutions, so you can always check your work or skip to the part of the book that interests you the most.

All the state libraries covered here come with a history that is not easy to know unless you’ve lived through it. For this reason, Aleks always starts each library’s section with some history: why was the library created, the problem it aims to solve, and the community’s response. This sets the scene and is followed by a technical explanation of how the library actually works. Finally, we see the library in action with some code examples and then use it ourselves in an app. This format really helps the reader understand the best use-case of each library and provides the information to help you make a more informed decision about which (if any) library to use in your own work.

This book is more than just a guide on state management. You can really feel the wealth of experience Aleks has gained through her years of working as a Software Engineer on real life projects. Throughout the book, she is often sprinkling in tips and tricks from her experience, from debugging tips to useful libraries to use. There are also plenty of links for additional reading for each section so you can dive deeper into anything that piques your interest. Especially as a newcomer to React Native, this book is a goldmine of information you didn’t know!

Kadi Kraman

Head of Mobile Dev at Formidable and Instructor at Frontend Masters and egghead.io

Contributors

About the author

Aleksandra Desmurs-Linczewska is a web and software developer with experience reaching as far as Flash and websites laid out with tables. Aleks has seen her fair share of diverse code bases, bugs, and Jira tickets. She studied French literature, but after graduating, she decided to opt for a career in IT, which has always interested her. She started out creating websites for friends and family. Soon, she landed her first paying job at a software house in Sopot, Poland. A few years later, she learned about React Native and started writing her first app back in 2018. She’s been working on both React JS and React Native since then. However, she strongly favors React Native. She personally published a weather app, and she participates in OSS projects and helps out with PRs, issues, and discussions. She recently started working for Callstack, the biggest React Native software house in Poland.

I want to thank my family – for understanding how much time writing a book can take. I’d also like to thank my team at Packt, for being so understanding of how long it took me to write this book. I would especially like to thank Inderpal, who found me and convinced me to try this, and Aamir for his never-ending patience toward me and his tireless work.

About the reviewers

Piyush Nanwani is an IT professional with three years of experience as a full-stack developer and has worked on designing, developing, and deploying software applications. Powered by his passion for technology, he has delivered more than six production-ready self-started projects. Currently, he is working as a mobile app developer with M/s. Atlantis Intelligence Ltd. A recent project of his was developing a low-code platform to build mobile apps. Currently, he is working on React Native, React JS, MS SQL, and .NET, among other things. He holds a B.Tech degree in computer science from IP University, New Delhi.

His interests include exploring new technologies, attending conferences, reading books, and dancing.

You can reach Piyush at https://www.linkedin.com/in/piiyush.

Ahir Jere is an experienced full-stack developer. He has worked with a variety of platforms, such as embedded systems and desktop and mobile applications, as well as cloud applications. Well-versed in Python and JavaScript, he has multiple applications powered by Django and Node.js and creates beautiful, vibrant UI applications with React and Flutter. These applications range from art galleries for showcasing peoples’ photography to large e-commerce stores with a wide variety of products and banking applications for different FinTech applications.

Table of Contents

Preface

Part 1 – Learn the Basics: Intro to React, States, Props, Hooks, and Context

1

What are React and React Native?

Understanding the history of ReactJS

The predecessors

And then there was React

Thinking in React (the React mindset)

Understanding cross-platform software development

Going over the history of React Native

Reviewing examples of popular apps using React Native

Summary

2

Managing State in a Simple React App

Technical requirements

What is state and how is it different from props?

What are stateful and stateless components?

What are hooks and why use them?

Which hooks should you know?

Setting up the example app

Environment setup

App structure

Summary

Further reading

Part 2 – Creating a Real, Working App

3

Planning and Setting Up the Funbook App

Technical requirements

Planning the needed surfaces and components

Planning data flows in the app

Getting comfortable previewing and debugging the app

Summary

Further reading

4

Styling and Populating the Funbook App

Technical requirements

Creating and styling components

Pulling in data for the app

Summary

Further reading

Part 3 – Exploring Various Libraries for State Management in React Native

5

Implementing Redux in Our Funbook App

Technical requirements

What is Redux? A brief history

Installing and configuring Redux

Dispatching actions

Adding Redux functionalities to the app

User login state walkthrough

Using Redux for liked images

Combining various pieces of global state

Taking advantage of Redux Toolkit for creating actions

Fetching data

Replacing the context

Debugging

Summary

Further reading

6

Using MobX as a State Manager in a React Native App

Technical requirements

Going over MobX concepts

Configuring MobX in the Funbook app

Using MobX for FavoritedImages

Creating the store

Fetching data

Adding actions

Deriving data from state

Summary

Further reading

7

Untangling Complex Flows in React Native Apps with XState

Technical requirements

What are finite state machines?

What is XState – high-level concepts

Configuring XState in the Funbook app

Using XState for the FavoritedImages surface

Configuring context and components

Fetching image data

Managing the image in the image modal

Liking images

Summary

Further reading

8

Integrating Jotai in a React Native App

Technical requirements

What is Recoil and an atomic state?

What is Jotai?

Configuring Jotai in the Funbook app

Using Jotai for ListOfFavoritedImages

Fetching data with Jotai

Reading and writing atoms

Adding read-write functionality to the imageListAtom

Implementing the Like button

Summary

Further reading

9

Using React Query for Server-Side-Driven State Management

Technical requirements

What is React Query and why is it in this book?

Installing and configuring React Query

Using React Query for data fetching

Fetching image data

Other React Query Functionalities

React Query utilities for React Native

Summary

Further reading

Part 4 – Summary

10

Appendix

Index

Other Books You May Enjoy

Part 1 – Learn the Basics: Intro to React, States, Props, Hooks, and Context

In this part, we will start with some theoretical knowledge that will be vital for creating a real app. The Readers will learn some of the history of React and its general rules, guidelines, and best practices. Next, we will look into React’s built-in strategies for dealing with states: local states, props, hooks, and context.

This part includes the following chapters:

Chapter 1, What are React and React Native?Chapter 2, Managing State in a Simple React App

1

What are React and React Native?

Welcome to the magical world of React and React Native. I hope to make you feel at home here. It’s okay if this is your very first contact with these frameworks, or you may have played around with them a little bit already. This book will focus on managing state in React Native apps, but we will start by going over the basics.

If React and React Native were people, the first one would be the parent of the second one. You can focus on the child framework, but you will find great benefits in getting to know the “parent” of React Native – ReactJS.

We will start this journey by going over the history of ReactJS and specifically, why it was created. We will then continue our study of ReactJS by looking into what it means to think in React or to have the React mindset. Once we’re familiar with ReactJS, we will try to understand what cross-platform software development means and what place React Native holds in the cross-platform development ecosystem. For understanding the ecosystem, we will concentrate on React Native itself, its brief history, and its current state. We will finish our tour with a handful of examples of native apps written in React Native.

In this chapter, we will cover the following topics:

Understanding the history of ReactJSThinking in React (the React mindset)Understanding cross-platform software developmentGoing over the history of React NativeReviewing examples of popular apps using React Native

By the end of this chapter, you will have high-level knowledge of React and React Native. You will also understand their place in the software development ecosystem.

Understanding the history of ReactJS

In this section, we will briefly look into the history of ReactJS. If you’re not interested in this particular topic, feel free to skip this section and go straight to Thinking in React. Knowing the history of a framework is not compulsory for using it. If you prefer condensed knowledge served in a YouTube pill, I highly recommend watching a 10-minute video called The Story of React, published on YouTube by uidotdev.

The predecessors

Did you know that the first website ever created is still live? You can find it here: http://info.cern.ch/hypertext/WWW/TheProject.html. It was created in 1991! A lot has changed since then. For starters, web developers wanted to change their websites’ appearance, hence CSS was created. A few years later those same web developers wanted to see more interactivity on their now beautiful websites. This is when JavaScript found its place on the internet. But as we know, the web never stops evolving. Heavy usage of JavaScript led to the creation of libraries such as jQuery, BackboneJS, and Ember. Each library’s creators learned lessons from their competitors. They made decisions that led to creating very different developer experiences. The developers had their preferences and little wars over which library is better.

There is no right answer to this question. What is certain, however, is that user experience on websites evolved, no matter which library was used behind the scenes. Websites became much more interactive and adaptable to the user’s screen size. For example, it is common practice today to create separate menus for mobile views and desktop views. This can be achieved with JavaScript, or CSS alone. This user experience shift could not take place without the evolution of JavaScript open source libraries.

After a few years of adding more and more separate bits of JavaScript to websites, it was time for a more holistic solution. The first breakthrough came from Google, with AngularJS. AngularJS, officially released in 2010, was different from other solutions on the market at that time. This was not just another library; this was a framework. Developers were able to create complex interactions quickly, and they were no longer afraid that any change to their JavaScript files could break the entire page. I don’t want to go into the implementational details of AngularJS. After all, that is not the focus of this book. In broad strokes, AngularJS introduced special HTML attributes that were observed by the framework running in the background. As you may imagine, when JavaScript is observing dozens or even hundreds of elements and events, it will slow down. So, the user experience is suffering, and the world is ready for another JavaScript revolution. Google thought they would remain king of the hill with their Angular version 2, but in 2013, Facebook developers announced the release of ReactJS.

And then there was React

ReactJS was presented specifically as a user interface (UI) library. It was conceived to be used for end user interactions on websites. It also used JSX – an extension to JavaScript created for React. Many developers reacted, pun intended, angrily to this new syntax. I would say though, that angry reactions are not unexpected in the world of tech. Any new technological solution has to weather the storm of angry Reddit posts saying that it’s ugly, useless, or simply terrible. Luckily for us, ReactJS developers did not stop working on their open source framework because of this initial negative reaction. Furthermore, developers who got to know ReactJS became its advocates. Why, you may ask, did ReactJS stand the test of time, while Angular hasn’t? I believe it has to do with the high-level mindset of the framework. ReactJS proposes elegant, simple solutions while staying completely configurable to any needs. I will go further into this mindset idea in the next section.

Going back to our history lesson! We’re in 2013, and ReactJS has entered the scene with a bang. Many people hate it, but others use it for more and more complex websites. And it turns out, unfortunately, that ReactJS does not scale well. Your React components use state and props. If the parent creates a state, which needs to be read four to five components lower in the hierarchy, you encounter something that is dubbed prop drilling. Prop drilling means that the developer has to pass the necessary prop through many parent components in order to get to the final child that needs to read it. This process is irritating and boring, at the same time! This is when the first state management library was created – Redux. We will talk in detail about Redux and other state management libraries in the next chapters.

As of writing this book, ReactJS is one of the most popular JavaScript libraries. It evolves constantly, and its maintainers are open to public discussions and suggestions. In 2019, they introduced hooks and context. These two React utilities can cover a lot of your state management needs. They were created because the React team realized that developers using React needed an improvement in the state management area.

A few years before the introduction of hooks and context, specifically in 2015, Facebook developers released React Native. The true hero of this book! But let’s not get ahead of ourselves. At this moment, it is important that you understand the basic concepts of React. Let’s move on to the React mindset.

Thinking in React (the React mindset)

The official ReactJS docs include a chapter called Thinking in React: https://reactjs.org/docs/getting-started.html#thinking-in-react.

Important note

Many React users credit reading Thinking in React (https://reactjs.org/docs/thinking-in-react.html) as the moment React finally clicked for them. It’s probably the oldest React walk-through but it’s still just as relevant.

Let’s try and capture the most important, and still relevant, parts of that article.

First of all, when we create a website with ReactJS, we need to think about how we will construct our components. Not HTML blocks, not DOM elements, but components. Ideally, each component will be a separate entity, which either creates a state or consumes props, or sometimes both. The component is the smallest part of our app, just like atoms are the smallest parts of our world.

Okay, I realize atoms can be further divided into neutrons, protons, and electrons. And ReactJS components can be