Hands-On Design Patterns with React Native - Mateusz Grzesiukiewicz - E-Book

Hands-On Design Patterns with React Native E-Book

Mateusz Grzesiukiewicz

0,0
36,59 €

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

Mehr erfahren.
Beschreibung

Learn how to write cross platform React Native code by using effective design patterns in the JavaScript world. Get to know industry standard patterns as well as situational patterns. Decouple your application with these set of “Idea patterns”.




Key Features



  • Mobile development in React Native should be done in a reusable way.


  • Learn how to build scalable applications using JavaScript patterns that are battle tested.


  • Try effective techniques on your own using over 80 standalone examples.






Book Description



React Native helps developers reuse code across different mobile platforms like iOS and Android.







This book will show you effective design patterns in the React Native world and will make you ready for professional development in big teams.







The book will focus only on the patterns that are relevant to JavaScript, ECMAScript, React and React Native. However, you can successfully transfer a lot of the skills and techniques to other languages. I call them “Idea patterns”.







This book will start with the most standard development patterns in React like component building patterns, styling patterns in React Native and then extend these patterns to your mobile application using real world practical examples. Each chapter comes with full, separate source code of applications that you can build and run on your phone.







The book is also diving into architectural patterns. Especially how to adapt MVC to React environment. You will learn Flux architecture and how Redux is implementing it. Each approach will be presented with its pros and cons. You will learn how to work with external data sources using libraries like Redux thunk and Redux Saga.







The end goal is the ability to recognize the best solution for a given problem for your next mobile application.




What you will learn



  • Explore the design Patterns in React Native


  • Learn the best practices for React Native development


  • Explore common React patterns that are highly used within React Native development


  • Learn to decouple components and use dependency injection in your applications


  • Explore the best ways of fetching data from the backend systems


  • Learn the styling patterns and how to implement custom mobile designs


  • Explore the best ways to organize your application code in big codebases





Who this book is for



The ideal target audience for this book are people eager to learn React Native design patterns who already know the basics of JavaScript. We can assume that the target audience already knows how to write Hello World in JavaScript and know what are the functions, recursive functions, JavaScript types and loops.

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

EPUB

Seitenzahl: 334

Veröffentlichungsjahr: 2018

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.



Hands-On Design Patterns with React Native

 

 

 

 

 

 

Proven techniques and patterns for efficient native mobile development with JavaScript

 

 

 

 

 

 

 

 

Mateusz Grzesiukiewicz

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

BIRMINGHAM - MUMBAI

Hands-On Design Patterns with React Native

Copyright © 2018 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.

Commissioning Editor:Amarabha BanerjeeAcquisition Editor:Devanshi DoshiContent Development Editor: Aishwarya GawankarTechnical Editor:Leena PatilCopy Editor: Safis EditingProject Coordinator:Sheejal ShahProofreader: Safis EditingIndexer:Tejal Daruwale SoniGraphics: Alishon MendonsaProduction Coordinator: Nilesh Mohite

First edition: September 2018

Production reference: 1280918

Published by Packt Publishing Ltd. Livery Place 35 Livery Street Birmingham B3 2PB, UK.

ISBN 978-1-78899-446-0

www.packtpub.com

 

To all the people who create interfaces that save our lives.
                                                                                       – Mateusz Grzesiukiewicz
  
mapt.io

Mapt is an online digital library that gives you full access to over 5,000 books and videos, as well as industry leading tools to help you plan your personal development and advance your career. For more information, please visit our website.

Why subscribe?

Spend less time learning and more time coding with practical eBooks and Videos from over 4,000 industry professionals

Improve your learning with Skill Plans built especially for you

Get a free eBook or video every month

Mapt is fully searchable

Copy and paste, print, and bookmark content

Packt.com

Did you know that Packt offers eBook versions of every book published, with PDF and ePub files available? You can upgrade to the eBook version at www.packt.com and as a print book customer, you are entitled to a discount on the eBook copy. Get in touch with us at [email protected] for more details.

At www.packt.com, you can also read a collection of free technical articles, sign up for a range of free newsletters, and receive exclusive discounts and offers on Packt books and eBooks. 

Contributors

About the author

Mateusz Grzesiukiewicz has worked on numerous big projects, including an investment banking platform at Goldman Sachs, a Jira project management tool at Atlassian, and a recruitment portal at GoldenLine. Every of these projects served millions of people, which made them great opportunities to test scalability and the industry's best design patterns. He strives to popularize the common patterns and help people grow their technology at scale. He has spent hundreds of hours teaching, for instance at a private programming school called Coder's Lab. He has over 5,000 students registered on his online React course on Udemy. He would love to bring programming to every household, hence this book—Hands-On Design Patterns with React Native.

 

Big thanks to all of the great editors who spent hours reading my silly drafts. To all of the people who kept me mentally safe while I worked 16 hours a day to deliver the quality this topic deserved. Bows to my family, who created warm and welcoming vibrations, especially those who will never understand a word of this book. To Jolanta and Dariusz, my parents.

 

About the reviewer

Tiago Guizelini is a senior full-stack developer from São Paulo, Brazil. He loves developing mobile apps using Android and React Native, building REST APIs with Java or Node.js, and frontend development with React.js and Angular.

I would like to thank my wife, Dayane, for supporting my work and understanding me as a person I am.

 

 

 

 

 

Packt is searching for authors like you

If you're interested in becoming an author for Packt, please visit authors.packtpub.com and apply today. We have worked with thousands of developers and tech professionals, just like you, to help them share their insight with the global tech community. You can make a general application, apply for a specific hot topic that we are recruiting an author for, or submit your own idea.

Table of Contents

Title Page

Copyright and Credits

Hands-On Design Patterns with React Native

Dedication

Packt.com

Why subscribe?

Packt.com

Contributors

About the author

About the reviewer

Packt is searching for authors like you

Preface

Who this book is for

What this book covers

To get the most out of this book

Download the example code files

Download the color images

Conventions used

Get in touch

Reviews

React Component Patterns

Stateless and stateful components

What are the advantages of stateless components?

Component composition

Composing the application layout

What about component inheritance?

Testing components on high-level patterns

Snapshot testing expandable components

Test-driven development approach

Presentational components

Decoupling styles

Container component

HOC

HOC composition

Examples of useful HOCs

Summary

View Patterns

Technical requirements

Introduction to JSX

JSX standard tricks

A beginner's guide to naming

Type checking with PropTypes

Built-in components you need to know about

The ScrollView component

The Image component

The TextInput component

The Button component

Touchable opacity

Building forms

Controlled inputs

Uncontrolled input

Introduction to error boundaries

How error boundaries catch errors

Understanding error boundaries

When to use error boundaries

Why Mixins are anti-patterns

Mixin example

Using HOCs instead

Linters and code style guide

Adding a linter to create a React Native app

Airbnb React style guide rules

Fixing errors

Summary

Styling Patterns

Technical requirements

How React Native styles work

Surprising styles inheritance

Workaround for limited inheritance

Learning unitless dimensions

Absolute and relative positioning

Using the Flexible Box pattern

Positioning items with Flexbox

Styling flex items

Styling content

Solving the text overflow problem

Scaling the font down

Truncating text

Using the Kilo social media notation

React Native animated

What are animations?

Changing attributes over time

The easing function

Scheduling events

Measuring FPS

How to measure FPS

Summary

Flux Architecture

One-direction dataflow pattern

React's one-way data binding

Event problems

Further issues with binding

Introduction to Flux

Replacing MVC

Flux by example

Detailed Flux diagram

What are side effects?

Why recognize side effects?

Working with side effects in MVC

Working with side effects in Flux

Summary

Questions

Further reading

Store Patterns

Using Redux stores

Minimal Redux application example

How Redux fits into Flux

Moving to Redux

Redux as a pattern

Core principles of Redux

Moving to a single source of truth

Creating an alternative with MobX

Moving to MobX

Using PropTypes with annotations

Comparing Redux and MobX

Using system storage in React Native

Effect patterns

Handling side effects

Summary

Further reading

Data Transfer Patterns

Preparation

Fetching data with the built-in function

Refactoring to activity indicator

Handling error scenarios

Naive stateful component fetching

The Thunk pattern and Redux Thunk

Lifting the state to Redux

Benefits of refactoring to Redux

Using Redux Thunk

Understanding the Thunk pattern

The saga pattern and Redux Saga

Introduction to the iterator pattern

The generator pattern

Redux Saga

Redux Saga benefits

Summary

Further reading

Navigation Patterns

React Native navigation alternatives

Designers navigation patterns

Navigation to top-level screens

Navigating between different levels of the graph

Navigating on the same level of the graph

Developers' navigation patterns

Restructuring your application

React Navigation

Using React Navigation

Multiple screens with React Navigation

Tab navigation

Drawer navigation

Issues with duplicated data

React Native Navigation

A few words on the setup

Basics of React Native Navigation

Further investigation

Summary

Further reading

JavaScript and ECMAScript Patterns

JavaScript and functional programming

ES6 map, filter, and reduce

Using reduce to reimplement filter and map

Counting items in an array

The iterator pattern

Defining a custom iterator

Using generators as a factory for iterators

Making an API call to fetch task details with a generator

Alternatives to generators

Selectors

Selecting from the Redux store

Caching the selectors

Learning functions from the Ramda library

Composing functions

Fighting the confusing code

Currying functions

Flipping

Summary

Further reading

Elements of Functional Programming Patterns

Mutable and immutable objects

Immutable primitives in JavaScript

Immutability cost explained

Benchmark on read/write operations

Pure functions

Pure functions in Redux

Caching pure functions

Referential transparency

Everything but monads

Call me Maybe

Monad interface requirements

Higher-order functions

Examples of higher-order functions

Functional languages aside

Terminology

Building abstractions

React is not obsessed with pure functions

Summary

Further reading

Managing Dependencies

The singleton pattern

Implementing the singleton pattern in ECMAScript

Why using the singleton pattern is discouraged

The many singleton flavors in JavaScript

ES6 modules and beyond

The DI pattern

Using the DI pattern with storybooks

Nested stories with DI

DI with React context

Using the React Context API

React Redux aside

Managing the code base

Quick wins

Establishing conventions

Summary

Further reading

Type Checking Patterns

Introduction to types

Introduction to TypeScript

Configuring TypeScript

Learning the basic types

enums and constants patterns

Creating union types and intersections

Generic types

Understanding TypeScript

Type inference

Structural typing

Immutability with TypeScript

readonly

Using linter to enforce immutability

Summary

Further reading

Other Books You May Enjoy

Leave a review - let other readers know what you think

Preface

Frameworks and libraries come and go. Design patterns usually stay for longer. In this book, we do a mix of learning React Native and design patterns relevant to this ecosystem. When it comes to React, the essential knowledge about design patterns is spread all over the place. Sometimes it's buried in proprietary code bases. This book brings it to you. I call them idea patterns: hands-on design patterns that are explained with real working examples. In this book we use React Native, but you can successfully use most of those patterns in web development with React, or even other frameworks, such as Angular or Vue. Hopefully you will use this knowledge to build well thought-out and easy-to-maintain code bases. Good luck with this endeavor!

Who this book is for

Amateur programmers and passionate people are very welcome to read this book, but expect that it may be more challenging than elementary programming books.

I assume you have some programming experience in JavaScript and that the terminal window is not foreign to you. Ideally, you should work as a developer (junior/mid/senior) so you will have a broad perspective and can immediately apply the knowledge to your work. Experience in developing mobile applications is not required.

What this book covers

Chapter 1, React Component Patterns, is the starting point of our journey. We need to understand the core building blocks of our application: React components. You will learn how to properly use presentational and container components.

Chapter 2, View Patterns, will dive into the best approaches into writing view code. You will learn the patterns that decouple view layer from the rest of the app. Also, in this chapter we learn about the basics of React Native: its most important components that are available out of the box. For the first time, our application code will be automatically tested by tooling such as Linter.

Chapter 3, Styling Patterns, is a chapter dedicated to design patterns built around styling. You get a look at the patterns that mobile designers need to follow. On top of that, we will learn Flexbox pattern and learn how to properly create and measure animations in React Native.

Chapter 4, Flux Architecture, finally looks at the architecture. Flux will enable us to scale our frontend code much more easily. For the first time, we will introduce Dispatcher and Stores into our application.

Chapter 5, Store Patterns, focuses on one important part of Flux: Store. You will learn about the Redux and Mobx state management libraries. By the end of the chapter, you will know how to make Store your application's single source of truth.

Chapter 6, Data Transfer Patterns, walks you through patterns that involve so-called side effects. We will use the local server and the API that our React Native code will consume. You will learn how to decouple such processes from the main application code using Redux Thunk and Redux Saga libraries

Chapter 7, Navigation Patterns, shows you the difficult part of the mobile application: navigation. We will dive into cross-platform problems and see how to handle them using either React Navigation or React Native Navigation.

Chapter 8, JavaScript and ECMAScript Patterns, starts with the JavaScript iterator pattern and then walks you through useful functions within JavaScript, ECMAScript, and in a Ramda library. After all that, we discuss some of the functional approaches that are related to the next chapter.

Chapter 9, Elements of Functional Programming Patterns, explores the unique world of Functional Programming patterns. Some of them are really famous in React and React Native applications. This chapter aims to explain why and helps you make a right decision if you should take more Functional Programming techniques into your project.

Chapter 10, Managing Dependencies, draws your attention to dependency injection, and how to avoid usage of Singleton pattern. You will learn about the React context API and see how libraries have been leveraging dependency injection in the past.

Chapter 11, Type Checking Patterns, teaches you how to type your application. We will do a walk-through of TypeScript's capabilities. By the end, you will be able to type the whole application. You will learn what nominal and structural typing are. 

To get the most out of this book

Take your time, don't rush. You don't need to read this book in a week.

Come back to this book as your developer career progresses. You will focus on completely different things, and this way you will learn the most out of this book.

Play with the examples I have prepared. Each is a standalone application so you can play and improve the code as we go. This is meant to serve as a playground so you can not only learn from the examples but create extensions of them. As you build, you will understand the changes that are introduced section after section. If you just read the book, you will definitely miss this perspective.

Download the example code files

You can download the example code files for this book from your account at www.packt.com. If you purchased this book elsewhere, you can visit www.packt.com/support and register to have the files emailed directly to you.

You can download the code files by following these steps:

Log in or register at

www.packt.com

.

Select the

SUPPORT

tab.

Click on

Code Downloads & Errata

.

Enter the name of the book in the

Search

box and follow the onscreen instructions.

Once the file is downloaded, please make sure that you unzip or extract the folder using the latest version of:

WinRAR/7-Zip for Windows

Zipeg/iZip/UnRarX for Mac

7-Zip/PeaZip for Linux

The code bundle for the book is also hosted on GitHub at https://github.com/Ajdija/hands-on-design-patterns-with-react-native. In case there's an update to the code, it will be updated on the existing GitHub repository.

We also have other code bundles from our rich catalog of books and videos available at https://github.com/PacktPublishing/. Check them out!

Download the color images

We also provide a PDF file that has color images of the screenshots/diagrams used in this book. You can download it here: https://www.packtpub.com/sites/default/files/downloads/9781788994460_ColorImages.pdf.

Conventions used

There are a number of text conventions used throughout this book.

CodeInText: Indicates code words in text, database table names, folder names, filenames, file extensions, pathnames, dummy URLs, user input, and Twitter handles. Here is an example: "Mount the downloaded WebStorm-10*.dmg disk image file as another disk in your system."

A block of code is set as follows:

export default function

() {

return

React.

createElement

( Text

,

{

style

: {

marginTop

:

30

}}

,

'Example Text!'

)

;

}

When we wish to draw your attention to a particular part of a code block, the relevant lines or items are set in bold:

export default

function

App() {

return

(

<View

style

{styles.

container

}

>

...

</View>

)

;

}

Any command-line input or output is written as follows:

yarn test -- --coverage

Bold: Indicates a new term, an important word, or words that you see onscreen. For example, words in menus or dialog boxes appear in the text like this. Here is an example: "You can now tap the Details button to navigate to the Task Details screen."

Warnings or important notes appear like this.
Tips and tricks appear like this.

Get in touch

Feedback from our readers is always welcome.

General feedback: If you have questions about any aspect of this book, mention the book title in the subject of your message and email us at [email protected].

Errata: Although we have taken every care to ensure the accuracy of our content, mistakes do happen. If you have found a mistake in this book, we would be grateful if you would report this to us. Please visit www.packt.com/submit-errata, selecting your book, clicking on the Errata Submission Form link, and entering the details.

Piracy: If you come across any illegal copies of our works in any form on the Internet, we would be grateful if you would provide us with the location address or website name. Please contact us at [email protected] with a link to the material.

If you are interested in becoming an author: If there is a topic that you have expertise in and you are interested in either writing or contributing to a book, please visit authors.packtpub.com.

Reviews

Please leave a review. Once you have read and used this book, why not leave a review on the site that you purchased it from? Potential readers can then see and use your unbiased opinion to make purchase decisions, we at Packt can understand what you think about our products, and our authors can see your feedback on their book. Thank you!

For more information about Packt, please visit packt.com.

React Component Patterns

Developing Android and iOS has never been easier than it is now. React Native has changed how fast we develop new apps and deliver value to the end user. Knowing this technology will give you a great edge in the market. I'm Matt and I'm happy to show you the best practices I have learned while working in a React Native ecosystem. Through this book, we will explore design patterns by example. In just this first chapter, we will create over 10 small applications. Later on in this book, we will create more complex applications, using the patterns that I will gradually introduce to you.

In this chapter, we will explore React patterns that also apply to the React Native world. The most crucial patterns you need to understand are stateless and stateful components. Understanding how to use these will make you a much better React Native developer and empower you with standard patterns in every React Native application.

When it comes to components, it is crucial to make them as reusable as possible and follow the well-known programmer principle—Don't Repeat Yourself (DRY). Presentational components and container components are meant to do just that. We will dive into them with a couple of examples to learn how to split features into reusable pieces.

To be more precise, in this first chapter, we will look at the following topics:

Stateless and stateful components, using short and then more complex examples

How to create reusable and easily configurable presentational components 

Container components and their role in the encapsulation of features

When to compose components and how to create

Higher Order Components

(

HOCs

)

It's time to act on your side. Prepare your environment for React Native development right now if you want to follow along and play with the examples. Most of the code samples that you will see in this book can be run and displayed either on a simulator or on a real mobile device. Now, make sure that you can launch the Hello World example on your mobile or simulator.

Code examples are checked into a Git repository on GitHub, which can be found at https://github.com/Ajdija/hands-on-design-patterns-with-react-native. Please follow the readme.md instructions to set up your machine and launch our first example. The Hello World example can be found in the following directory src/Chapter_1_React_component_patterns/Example_1_Hello_World.

What are the advantages of stateless components?

It may seem tempting to only use stateful class components and develop a whole application like that. Why would we even bother with stateless functional components? The answer is performance. Stateless functional components can be rendered faster. One of the reasons why this is the case is because stateless functional components do not require some of the life cycle hooks.

What are life cycle hooks? React components have life cycles. This means that they have different stages like mounting, unmounting, and updating. You can hook each stage and even sub stage. Please check the official React documentation to see the full list of available life cycle methods: https://reactjs.org/docs/state-and-lifecycle.html.These are useful to trigger fetching data from the API or to update the view.

Please note that if you are using React v16 or later, it is not true that functional components are wrapped into class components internally within the React library:

"Functional components in React 16 don't go through the same code path as class components, unlike in the previous version where they were converted to classes and would have the same code path. Class components have additional checks that are required and overhead in creating the instances that simple functions don't have. These are micro-optimizations though and shouldn't make a huge difference in real-world apps – unless your class component is overly complex."- Dominic Gannaway, engineer on the React core team at Facebook (https://github.com/reactjs/reactjs.org/issues/639#issuecomment-367858928)

Functional components are faster, but in most cases are outperformed by class components extending React.PureComponent:

"Still, to be clear, they don't bail out of rendering like PureComponent does when props are shallowly equal."- Dan Abramov, co-author of Redux and Create React App, engineer on the React core team at Facebook (https://twitter.com/trueadm/status/916706152976707584)

Functional components are not only more concise, but they usually are also pure functions. We will explore this concept further in Chapter 9, Elements of Functional Programming Patterns. Pure functions provide a lot of benefits, such as a predictable UI and easy tracking of user behavior. The application can be implemented in a certain way to record user actions. Such data helps with debugging and reproducing errors in tests. We will dig into this topic later on in this book.

What about component inheritance?

"At Facebook, we use React in thousands of components, and we haven't found any use cases where we would recommend creating component inheritance hierarchies."- React official documentation (https://reactjs.org/docs/composition-vs-inheritance.html)

I have not come across a situation where I had to step away from component composition in favor of inheritance. Neither have developers at Facebook (as per the preceding quotation). Hence, I highly recommend you get used to composition.

Testing components on high-level patterns

Testing is something very important when it comes to creating reliable and stable applications. First of all, let's look at the most common three types of tests you will need to write:

Trivial unit tests

: I don't understand it, but is it working or not working at all? 

Usually, tests that check whether the component renders or whether the function runs with no errors are called trivial unit tests

. If you do this manually, you call these tests smoke tests. Such tests are vital to have. Whether you like it or not, you should write trivial tests, at least to know if every feature is

somehow

working.

Unit tests

Does the code work as I expect it to? Does it work in all of the code branches? By branch, we mean places in the code where it branches, for instance, if statements are branching code into different code paths, which is similar to switch-case statements. Unit testing refers to testing a single unit of code. In crucial features of an application, unit tests should cover whole function code (as a principle: 100% code coverage for crucial features).

Snapshot tests

: Testing if the previous and actual version produce the same result is called snapshot testing. Snapshot tests are 

just creating text output

, but once the output is proven to be correct (through developer assessment and code review), it may work as a comparison tool. Try to use snapshot tests a lot. Such tests should be committed into your repository and undergo review process. This new feature in Jest saves a lot of time for developers:

Image snapshot tests:

In Jest, snapshot tests compare text (JSON to JSON), however, you may encounter references to snapshot tests on mobile devices, where this means comparing images to images. This is a more advanced topic, but is commonly used by big websites. Taking such a screenshot most likely requires building the whole app instead of a single component. Building the whole app is time-consuming, so some companies only run these type of tests when they plan for a release, for instance, on a release candidate build. This strategy can be automated to follow

continuous integration

and

continuous delivery

principles.

Since we are using the CRNA toolbox in this book, the testing solution you want to check is Jest (https://facebook.github.io/jest/).