Discover millions of ebooks, audiobooks, and so much more with a free trial

From $11.99/month after trial. Cancel anytime.

React Design Patterns and Best Practices
React Design Patterns and Best Practices
React Design Patterns and Best Practices
Ebook577 pages5 hours

React Design Patterns and Best Practices

Rating: 0 out of 5 stars

()

Read preview

About this ebook

About This Book
  • Dive into the core patterns and components of React.js in order to master your application's design
  • Improve their debugging skills using the DevTools
  • This book is packed with easy-to-follow examples that can be used to create reusable code and extensible designs
Who This Book Is For

If you want to increase your understanding of React and apply it to real-life application development, then this book is for you.

LanguageEnglish
Release dateJan 13, 2017
ISBN9781786468307
React Design Patterns and Best Practices

Related to React Design Patterns and Best Practices

Related ebooks

Programming For You

View More

Related articles

Reviews for React Design Patterns and Best Practices

Rating: 0 out of 5 stars
0 ratings

0 ratings0 reviews

What did you think?

Tap to rate

Review must be at least 10 words

    Book preview

    React Design Patterns and Best Practices - Michele Bertoli

    Table of Contents

    React Design Patterns and Best Practices

    Credits

    About the Author

    About the Reviewer

    www.PacktPub.com

    Why subscribe?

    Customer Feedback

    Preface

    What this book covers

    What you need for this book

    Who this book is for

    Conventions

    Reader feedback

    Customer support

    Downloading the example code

    Errata

    Piracy

    Questions

    1. Everything You Should Know About React

    Declarative programming

    React elements

    Unlearning everything

    Common misconceptions

    Summary

    2. Clean Up Your Code

    JSX

    Babel

    Hello, World!

    DOM elements and React components

    Props

    Children

    Differences with HTML

    Attributes

    Style

    Root

    Spaces

    Boolean attributes

    Spread attributes

    JavaScript templating

    Common patterns

    Multi-line

    Multi-properties

    Conditionals

    Loops

    Control statements

    Sub-rendering

    ESLint

    Installation

    Configuration

    React plugin

    Airbnb configuration

    The basics of functional programming

    First-class objects

    Purity

    Immutability

    Currying

    Composition

    FP and user interfaces

    Summary

    3. Create Truly Reusable Components

    Creating classes

    The createClass factory

    Extending React.Component

    The main differences

    Props

    State

    Autobinding

    Stateless functional components

    Props and context

    The this keyword

    State

    Lifecycle

    Refs and event handlers

    No reference to component

    Optimization

    The state

    External libraries

    How it works

    Asynchronous

    React lumberjack

    Using the state

    Derivables

    The render method

    Prop types

    React Docgen

    Reusable components

    Living style guides

    Summary

    4. Compose All the Things

    Communication between components

    Children

    Container and Presentational pattern

    Mixins

    Higher-order Components

    Recompose

    Context

    Function as Child

    Summary

    5. Proper Data Fetching

    Data flow

    Child-parent communication (callbacks)

    Common parent

    Data fetching

    React-refetch

    Summary

    6. Write Code for the Browser

    Forms

    Uncontrolled components

    Controlled components

    JSON schema

    Events

    Refs

    Animations

    React motion

    Scalable Vector Graphics

    Summary

    7. Make Your Components Look Beautiful

    CSS in JS

    Inline styles

    Radium

    CSS Modules

    Webpack

    Setting up a project

    Locally scoped CSS

    Atomic CSS Modules

    React CSS Modules

    Styled Components

    Summary

    8. Server-Side Rendering for Fun and Profit

    Universal applications

    Reasons to implement Server-Side Rendering

    SEO

    A common code base

    Better performance

    Don't underestimate the complexity

    A basic example

    A data fetching example

    Next.js

    Summary

    9. Improve the Performance of Your Applications

    Reconciliation and keys

    Optimization techniques

    Should component update

    Stateless functional components

    Common solutions

    Why did you update?

    Creating functions inside the render method

    Constants props

    Refactoring and good design

    Tools and libraries

    Immutability

    Monitoring tools

    Babel plugins

    Summary

    10. About Testing and Debugging

    The benefits of testing

    Painless JavaScript testing with Jest

    Mocha is a flexible testing framework

    JavaScript testing utilities for React

    A real-world testing example

    React tree Snapshot Testing

    Code coverage tools

    Common testing solutions

    Testing Higher-Order Components

    The Page Object pattern

    React Dev Tools

    Error handling with React

    Summary

    11. Anti-Patterns to Be Avoided

    Initializing the state using props

    Mutating the state

    Using indexes as a key

    Spreading props on DOM elements

    Summary

    12. Next Steps

    Contributing to React

    Distributing your code

    Publishing a npm package

    Summary

    React Design Patterns and Best Practices


    React Design Patterns and Best Practices

    Copyright © 2017 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, and its dealers and distributors will be held liable for any damages caused or alleged to be 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.

    First published: January 2017

    Production reference: 1100117

    Published by Packt Publishing Ltd.

    Livery Place

    35 Livery Street

    Birmingham 

    B32PB, UK.

    ISBN 978-1-78646-453-8

    www.packtpub.com

    Credits

    About the Author

    Michele Bertoli is a frontend engineer with a passion for beautiful UIs. Born in Italy, he moved to London with his family to look for new and exciting job opportunities. He has a degree in computer science and loves clean and well-tested code. Currently, he is working with React.js, crafting modern JavaScript applications. He is a big fan of open source and is always trying to learn something new. 

    I would like to thank my wife and my son for making my days better with their smiles. Dante, I hope the time I spent writing the book instead of playing with you will make sense when you are older, and you will be proud of me. I would also like to thank Packt Publishing for giving me this opportunity.

    About the Reviewer

    Clay Diffrient is a JavaScript enthusiast who is always looking to improve and do more. He currently works mostly in React, but has proficiency with other frameworks and libraries, such as Angular, Backbone, and jQuery. He is a maintainer of the popular react-modal library. He takes joy in creating software that is accessible for all people.

    Clay currently works as a software engineer at Instructure, where they make software that makes people smarter. He currently works on Instructure's flagship product, Canvas, an open source learning management system.

    Clay has previously reviewed MEAN Web Development (ISBN: 9781783983285), and enjoys being involved with the community.

    I wish to thank my wife Rachael and my two sons, Roger and Beau, for their unending support of my continual learning.

    www.PacktPub.com

    For support files and downloads related to your book, please visit www.PacktPub.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.PacktPub.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.PacktPub.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.

    https://www.packtpub.com/mapt

    Get the most in-demand software skills with Mapt. Mapt gives you full access to all Packt books and video courses, as well as industry-leading tools to help you plan your personal development and advance your career.

    Why subscribe?

    Fully searchable across every book published by Packt

    Copy and paste, print, and bookmark content

    On demand and accessible via a web browser

    Customer Feedback

    Thank you for purchasing this Packt book. We take our commitment to improving our content and products to meet your needs seriously-that's why your feedback is so valuable. Whatever your feelings about your purchase, please consider leaving a review on this book's Amazon page. Not only will this help us, more importantly it will also help others in the community to make an informed decision about the resources that they invest in to learn.

    You can also review for us on a regular basis by joining our reviewers' club. If you're interested in joining, or would like to learn more about the benefits we offer, please contact us: [email protected].

    Preface

    Taking a complete journey through the most valuable design patterns in React, this book demonstrates how to apply design patterns and best practices in real-life situations, whether it’s for new or already existing projects. It will help you make your applications more flexible, perform better, and easier to maintain-giving your workflow a huge boost when it comes to speed, without reducing quality.

    We’ll begin by understanding the internals of React before gradually moving on to writing clean and maintainable code. We’ll build components that are reusable across the application, structure applications, and create forms that actually work.

    Then, we’ll style React components and optimize them to make applications faster and more responsive. Finally, we’ll write tests effectively, and you’ll learn how to contribute to React and its ecosystem.

    By the end of the book, you’ll be saved from a lot of trial and error and developmental headaches, and you will be on the road to becoming a React expert.

    What this book covers

    Chapter 1, Everything You Should Know About React, introduces you to the base concepts of React, seen from an advanced perspective.

    Chapter 2, Clean Up Your Code, teaches that one of the most important aspects of writing maintainable code is to keep it clean and follow a coding style guide. To use React, it is also important to know the basics of functional programming.

    Chapter 3, Create Truly Reusable Components, informs that building an application using components is a key factor, but creating truly reusable components is the most important thing to do in order to keep the codebase clean and maintainable.

    Chapter 4, Compose All the Things, says that real applications are created using different components and it's important to make them communicate effectively, organizing and structuring the hierarchy in the right way.

    Chapter 5, Proper Data Fetching, instructs that any client-side application has to deal with data at some point; it takes you through the different techniques and approaches that can be used to fetch data in the React-way.

    Chapter 6, Write Code for the Browser, states that our applications live in the browser and we should know how to use it properly. This chapter will go through some advanced concepts, such as events, animations, and how to interact with the DOM.

    Chapter 7, Make Your Components Look Beautiful , demonstrates that crafting beautiful UI components is a big part of the frontend engineering work. With React, there are different ways of doing it and each one tackles the problem from a different perspective. It's important to know which libraries are available and how they work in order to choose the right one.

    Chapter 8, Server-Side Rendering for Fun and Profit, instructs that one of the greatest features of React is the server-side rendering. It works out of the box, but it's important to learn how to use it in the right way to get the most out of it.

    Chapter 9, Improve the Performance of Your Applications, informs that on the Web, performance is one of the most important factors to engage users. React offers a set of tools and techniques to create lightning-fast applications, and this chapter goes through all of them.

    Chapter 10,  About Testing and Debugging, makes you realize that we all want our applications to be stable and handle all the edge cases: tests help with that. Writing a comprehensive set of tests is vital to creating rock-solid and maintainable code. On the other hand, bugs always happen and it's crucial to know how to debug and find an issue as early as possible.

    Chapter 11,  Anti-Patterns to Be Avoided, explains the fact that developers often try to use shortcuts and creative solutions, but in some cases these workarounds can be dangerous for their applications, especially with big teams and large codebases. This chapter takes you through the common anti-patterns to be avoided while using React.

    Chapter 12, Next Steps, is the last chapter, and all the topics have been covered. I believe it's important to mention how to open source components (to give back to the community) and how to contribute to React and its ecosystem.

    What you need for this book

    We will need a computer with a terminal, a node.js/npm environment, and a browser.

    Who this book is for

    If you want to increase your understanding of React and apply it to real-life application development, this book is for you.

    Conventions

    In this book, you will find a number of text styles that distinguish between different kinds of information. Here are some examples of these styles and an explanation of their meaning.

    Code words in text, database table names, folder names, filenames, file extensions, pathnames, dummy URLs, user input, and Twitter handles are shown as follows: Inside the loop, there is some conditional logic to check if the #first and the #link properties exist, and depending on their values, a different piece of HTML is rendered. Variables are wrapped into curly braces.

    A block of code is set as follows:

    const toLowerCase = input => {

      const output = []

      for (let i = 0; i < input.length; i++) {

        output.push(input[i].toLowerCase())

      }

      return output

    }

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

    npm install -g create-react-app

    New terms and important words are shown in bold. Words that you see on the screen, for example, in menus or dialog boxes, appear in the text like this: Let's begin updating the tests, starting with the renders with text ones.

    Note

    Warnings or important notes appear in a box like this.

    Tip

    Tips and tricks appear like this.

    Reader feedback

    Feedback from our readers is always welcome. Let us know what you think about this book-what you liked or disliked. Reader feedback is important for us as it helps us develop titles that you will really get the most out of. To send us general feedback, simply e-mail [email protected], and mention the book's title in the subject of your message. If there is a topic that you have expertise in and you are interested in either writing or contributing to a book, see our author guide at www.packtpub.com/authors.

    Customer support

    Now that you are the proud owner of a Packt book, we have a number of things to help you to get the most from your purchase.

    Downloading the example code

    You can download the example code files for this book from your account at http://www.packtpub.com. If you purchased this book elsewhere, you can visit http://www.packtpub.com/support and register to have the files e-mailed directly to you.

    You can download the code files by following these steps:

    Log in or register to our website using your e-mail address and password.

    Hover the mouse pointer on the SUPPORT tab at the top.

    Click on Code Downloads & Errata.

    Enter the name of the book in the Search box.

    Select the book for which you're looking to download the code files.

    Choose from the drop-down menu where you purchased this book from.

    Click on Code Download.

    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/PacktPublishing/React-Design-Patterns-and-Best-Practices. We also have other code bundles from our rich catalog of books and videos available at https://github.com/PacktPublishing/. Check them out!

    Errata

    Although we have taken every care to ensure the accuracy of our content, mistakes do happen. If you find a mistake in one of our books-maybe a mistake in the text or the code-we would be grateful if you could report this to us. By doing so, you can save other readers from frustration and help us improve subsequent versions of this book. If you find any errata, please report them by visiting http://www.packtpub.com/submit-errata, selecting your book, clicking on the Errata Submission Form link, and entering the details of your errata. Once your errata are verified, your submission will be accepted and the errata will be uploaded to our website or added to any list of existing errata under the Errata section of that title.

    To view the previously submitted errata, go to https://www.packtpub.com/books/content/supportand enter the name of the book in the search field. The required information will appear under the Errata section.

    Piracy

    Piracy of copyrighted material on the Internet is an ongoing problem across all media. At Packt, we take the protection of our copyright and licenses very seriously. If you come across any illegal copies of our works in any form on the Internet, please provide us with the location address or website name immediately so that we can pursue a remedy.

    Please contact us at [email protected] with a link to the suspected pirated material.

    We appreciate your help in protecting our authors and our ability to bring you valuable content.

    Questions

    If you have a problem with any aspect of this book, you can contact us at [email protected], and we will do our best to address the problem.

    Chapter 1. Everything You Should Know About React

    Hello, readers!

    This book assumes that you already know what React is and what problems it solves for you. You may have written a small/medium application with React and you want to improve your skills and answer all your open questions.

    You should know that React is maintained by developers at Facebook and hundreds of contributors within the JavaScript community.

    React is one of the most popular libraries for creating user interfaces and it is well-known to be fast, thanks to its smart way of touching the DOM.

    It comes with JSX, a new syntax to write markup in JavaScript, which requires you to change your mind regarding the separation of concerns. It has many cool features, such as the server-side rendering that gives you the power to write Universal applications.

    To follow this book, you will need to know how to use the terminal to install and run npm packages in your Node.js environment.

    All the examples are written in ES2015, which you should be able to read and understand.

    In this first chapter, we will go through some basics concepts which are important to master to use React effectively, but are non-trivial to figure out for beginners:

    The difference between imperative and declarative programming

    React components and their instances, and how React uses elements to control the UI flow

    How React changes the way we build web applications, enforcing a different new concept of separation of concerns, and the reasons behind its unpopular design choice

    Why people feel the JavaScript Fatigue and what you can do to avoid the most common errors developers make when approaching the React ecosystem

    Declarative programming

    Reading the React documentation or blog posts about React, you have surely come across the term declarative.

    In fact, one of the reasons why React is so powerful is because it enforces a declarative programming paradigm.

    Consequently, to master React, it is important to understand what declarative programming means and what the main differences between imperative and declarative programming are.

    The easiest way to approach the problem is to think about imperative programming as a way of describing how things work, and declarative programming as a way of describing what you want to achieve.

    A real-life parallel in the imperative world would be entering a bar for a beer, and giving the following instructions to the bartender:

    Take a glass from the shelf

    Put the glass in front of the draft

    Pull down the handle until the glass is full

    Pass me the glass

    In the declarative world, instead, you would just say: Beer, please.

    The declarative approach of asking for a beer assumes that the bartender knows how to serve one, and that is an important aspect of the way declarative programming works.

    Let's move into a JavaScript example, writing a simple function that, given an array of uppercase strings, returns an array with the same strings in lowercase:

    toLowerCase(['FOO', 'BAR']) // ['foo', 'bar']

    An imperative function to solve the problem would be implemented as follows:

    const toLowerCase = input => {

      const output = []

      for (let i = 0; i < input.length; i++) {

        output.push(input[i].toLowerCase())

      }

      return output

    }

    First of all, an empty array to contain the result gets created. Then, the function loops through all the elements of the input array and pushes the lowercase values into the empty array. Finally, the output array gets returned.

    A declarative solution would be as follows:

    const toLowerCase = input => input.map(

      value => value.toLowerCase()

    )

    The items of the input array are passed to a map function, which returns a new array containing the lowercase values.

    There are some important differences to note: the former example is less elegant and it requires more effort to be understood. The latter is terser and easier to read, which makes a huge difference in big code bases, where maintainability is crucial.

    Another aspect worth mentioning is that in the declarative example, there is no need to use variables nor to keep their values updated during the execution. Declarative programming, in fact, tends to avoid creating and mutating a state.

    As a final example, let's see what it means for React to be declarative.

    The problem we will try to solve is a common task in web development: showing a map with a marker.

    The JavaScript implementation (using the Google Maps SDK) is as follows:

    const map = new google.maps.Map(document.getElementById('map'), {

      zoom: 4,

      center: myLatLng,

    })

    const marker = new google.maps.Marker({

      position: myLatLng,

      title: 'Hello World!',

    })

    marker.setMap(map)

    It is clearly imperative, because all the instructions needed to create the map, and create the marker and attach it to the map are described inside the code, one after the other.

    A React component to show a map on a page would look like this instead:

     

    In declarative programming, developers only describe what they want to achieve and there's no need to list all the steps to make it work.

    The fact that React offers a declarative approach makes it easy to use, and consequently, the resulting code is simple, which often leads to fewer bugs and more maintainability.

    React elements

    This book assumes that you are familiar with components and their instances, but there is another object you should know if you want to use React effectively: the Element.

    Whenever you call createClass, extend Component, or simply declare a stateless function, you are creating a component. React manages all the instances of your components at runtime, and there can be more than one instance of the same component in memory at a given point in time.

    As mentioned previously, React follows a declarative paradigm, and there's no need to tell it how to interact with the DOM; you just declare what you want to see on the screen and React does the job for you.

    As you might have already experienced, most other UI libraries work in the opposite way: they leave the responsibility of keeping the interface updated to the developer, who has to manage the creation and destruction of the DOM elements manually.

    To control the UI flow, React uses a particular type of object, called element, which describes what has to be shown on the screen. These immutable objects are much simpler compared to the components and their instances, and contain only the information that is strictly needed to represent the interface.

    The following is an example of an element:

    {

      type:

    Enjoying the preview?
    Page 1 of 1