Learning React

Learning React

01 / React: Getting Started | by Samer Buna *4

Course notes:

JS ES6 Important:

At the end: https://github.com/jscomplete/rgs-star-match

02 / React Fundamentals | by Liam McLennan *2

Low quality and quite outdated. I’ll outline interesting parts anyway…

  • Using example form library: react-jsonschema-form I’ll use React Hook Form as the most logical to me.

  • Model-View-Intent architecture mentioned

  • Custom State container is not hard to make, but using Redux or any other library is great because of standardization.

  • Reducer is function that takes an intent and current state and produces new updated state. Reducer is called like that, because reduces the stream of intents to the single object: application state.

  • In Redux, “Actions” are synonym to “Intents” Provider, connect and x: those are from React-redux, not from Redux only, to help in integrating React & Redux. redux & react-redux

  • For simple components, it is better only to pass state via props and not use State Container, as those components are far more reusable.

  • Chrome extension: Redux DevTools

03 / Using React Hooks | by Peter Kellner *3

Not amazed :(

Code: pkellner/pluralsight-course-using-react-hooks

React hooks are ONLY available in React functional components.

  • The React team recommends using multiple useState calls, as opposed to calling it once with object.

  • You can think of useEffect Hook as componentDidMount, componentDidUpdate, and componentWillUnmount combined Data fetching, manually changing the DOM in React components are all examples of side effects.

    • Using the Effect Hook React guarantees the DOM has been updated by the time it runs the effects.

    • If your effect returns a function, React will run it when it is time to clean up.

  • Enforce Rules of Hooks using ESLint. Plugin is included by default in Create React App.

  • Explanation: Memoization is optimization technique for returning cached results.

  • My simple explanation:

    • useRef: to target DOM element. Mutating the .current property via useRef doesn’t cause a re-render.
    • useState: to change local state
    • useEffects: for “component lifecycle” methods
    • useContext: for global state, to store data
    • useReducer: similar to useState but expanded, typically with action types and “dispatch” paradigm. Great for centralized global state using useContext, to define how state data changes
    • useCallback & useMemo: first one caches a function, second cashes a value. Performance reasons only (minimize rerendering)
  • Usage patterns:

  • Comparison with or without hooks: using-react-hooks/04/migrating-your-existing-apps-to-react-hooks-slides.pdf

  • Simple REST API from JSON file: typicode/json-server and interesting marmelab/json-graphql-server

  • Authentication using node.js Passport.js

05 / Building Scalable React Apps | by Hendrik Swanepoel *1

Really not current anymore. Using tech that are already almost obsolete and replaced by more modern approaches. Please don’t use: Redux Saga, Generators (yield), etc

Everything is revolving around react-boilerplate and components using container pattern. That’s why it was named “Scalable”!

06 / TypeScript: The Big Picture | by Simon Allardice *5

Introduction. Real pleasure: everything is top notch!

07 / AI: Executive Briefing | by Simon Allardice *5

Great introduction. Thank you!

  • Algorithmic Bias

  • Black Box of AI: when we train a model, what you get from it is an answer. What you don’t get is an explanation of that answer. This is sometimes called the black box of machine learning.

08 / Machine Learning: Executive Briefing | by Simon Allardice *5

  • Machine learning is not a new way to solve the kinds of problems you’re already familiar with. Machine learning as a way to solve new kinds of problems.

  • Our definition: Machine learning allows it to take existing data, analyze it to identify patterns, and use the results to make better predictions about new data.

  • … do the programmers in my organization need to write these machine learning algorithms? No. The vast majority, the overwhelmingly vast majority of companies and individuals do not need to write and never need to write machine learning algorithms. Instead, we’ll take a machine learning algorithm that somebody else has already written and we will apply it to our data. But Simon, you say, you’re telling me we can just pick some machine learning algorithm off the shelf and just feed our data into it? Well, a bit oversimplified, but kind of, yes.

    … I don’t want to suggest it’s as simple as just clicking a button. No, this is another part where you can’t remove the human because even though we may not write these machine learning algorithms, there’s still a lot of work to do in choosing the correct algorithm, applying it and configure it and testing it. And this is another part that takes time, attention, and most importantly, understanding what it is we’re actually trying to accomplish with our data. Now if you have a classic team of people working on machine learning projects, this would be one of the responsibilities of the data scientist role.

  • ML Algorithms:

    • Classification. It can be two-class (binary) classification or it can be multi-class classification
    • We also have a category called regression. Regression is what we use when the prediction we want is an actual number, an amount
  • Supervised and unsupervised learning, for example: clustering, anomaly detection, etc

  • … Let me recap and summarize the main situations that machine learning’s really good at:

    • Classification = I need to know what this thing is.
    • There’s regression = I need to know the value of this.
    • There’s clustering = Help me understand the structure of all of this data
    • And there’s anomaly detection = huh, that’s weird.

09 / Building Applications with React and Flux | by Cory House

Very, very good!

Completely updated course in fall of 2019 with latest patterns and libraries! Assumes no previous knowledge to React. It’s essentially from beginning, which is good.

  • Forms a package with “Building Applications with React and Redux” course from same author

  • Will talk about Flux paradigm for uni-directional data flow; a.k.a. state management; I need that!

  • Is using json-server as mock API (sample: /03/demos/after/tools)

  • Tricks for NPM scripts in package.json:

    • if you put pre as in prestart it executes everytime before start
    • run-p for run parallel (both server and JSON API server)
  • A note: compared to HTML, JSX fails with exact line with error; that’s great

  • Vue, Angular, Ember all put “JS” in HTML, but React puts “HTML” inside JS; and that’s better

  • Function components benefits: avoid “this” keyword and no need for “bind”, smaller, less “code noise”, easy to test as they are pure functions. So, always use functional components; always with hooks.

  • My observation: can’t use array index as a key, because for example: Index as a key is an anti-pattern. You can always use “surrogate key” with something like shortId or uuid

  • The simplicity of composing components is one of the main React great features

  • He uses a term “Controller View” for Container component (Container vs Presentation) aka Smart component (Smart vs Dumb)

  • Typescript: we have propTypes solved, and for defaultProps it is standard JavaScript default function parameters

  • As Primary “router” Component of React Router, we can use both HashRouter, MemoryRouter for no URL changes (React Native?) or standard BrowserRouter Routers

  • React Router for client-side routing

    • for a 404 page, we need and a without “path”
    • you can redirect with using state or you can directly communicate with history via props.history.push
    • we can add to “block page transitions”… that’s interesting and rarely used
  • Use debugger JavaScript statement to stop execution in Chrome DevTools, same function as setting a breakpoint; he is using it to inspect what has being passed as props to a component

  • React Forms

    • explaned how to have just single “change handler” by using the “name” property of an input field. See handleChange; we use something called “computed property” in JavaScript

    • Using teact-toastify for notifications; and toast.success, etc

    • He is using hid “pattern” for form validations (search for formIsValid() and .keys)

  • About file structure…

    • He is placing all the API functions in modules inside src/api folder, as standalone functions.
    • He is using src/components/common for all components that are not “tied to the page”; aka shared
    • All the server-side node.js code is placed inside /tools folder, together with .json database file
    • later on, when introduced testing in course #10, he put every component in separate folder
  • Flux

    • …making data calls from components will start creating “maintainability issues”
    • it is State Management Pattern popularized by Facebook

In summary, Flux is a pattern for unidirectional data flows that’s composed of three core pieces:

  • actions, which encapsulate events, such as a user clicking on a button;
  • stores (multiple), which hold application state, and you can have one store if your app is simple or multiple stores if you find that it helps;
  • and a dispatcher (one), which is the centralized hub. It’s a singleton (centralized list of callback functions), so there’s only one per app. The dispatcher holds references to callbacks so that it knows what stores to notify as actions occur. Once the store is updated, any subscribed React components are notified when the dispatcher emits an event.

Flux has many alternative implementations that are similar to what we just discussed, but the most popular is Redux

  • Flux

    • Actions; action creators describe all the actions that are possible Typically triggered on two places: by the user in UI, and from the server on page load or on errors during calls to the server Action payload contains type (required and named like that) and data (and optional with any name)
    • Dispatcher; distributes actions to stores; broadcasts payload to registered callbacks and send actions to stores … good to have Constants file here as it keeps things organized
    • Stores;
      • only Controller View components (aka Container aka Smart) should interact with the stores; Child components will be auto-updated via the props Avoid nesting Controller View components; recommends single Container component per page (or per portion of the page)
  • Nice metaphor “Chat With Flux” like there are 4 different people

  • Flux is similar but not the same as “publish-subscribe” pattern

  • We are using “Constants file” because those same action types will be used both in action creator functions and in the store, so it’s better to have it in separate file so autocompletion will work. “Constants file” will contain a list of all the action types we use in our system.

  • To help us with “observer” pattern; we’ll use EventEmitter class from Node.js library Events, but in browser with npm/events. You do not have to install events yourself: if your code runs in Node.js, events is built in and if code runs in the browser, bundlers like webpack also include the events module by default Read more: Observer Pattern and Pub-Sub with NodeJS Event Emitters

  • By Flux convection, each store has to have:

    • addChangeListener (wraps on)
    • removeChangeListener (wraps removeListener)
    • emitChange (wraps emit)
  • Every store is notified of every action; Store’s registration in dispatcher: this is a place where Flux’s dispatcher implementation differs from traditional publish-subscribe patterns. Every store that registers with the dispatcher is notified of every single action. So here we need to add some logic that switches based on the actionType that’s being passed, to determine if action is destined for this store.

  • My take: UI is subscribed to store, stores are subscribed to dispatcher’s actions, that in turn are generated from UI

10 / Building Applications with React and Redux | by Cory House

  • Redux is de-facto Flux implementation State alternatives are huge: ReactStateMuseum: tour of React state management systems

  • Redux main difference to Flux?

    • only one store in app
    • less boilerplate; no EventEmitter for subscribing components to store
    • no dispatcher at all
    • friendly to server rendering (isomorphic)
    • immutable store? (hot reloading, time-travel debugging)
    • very very small (2K)
  • Dan Abramov is Redux author (hired by Facebook in 2016) Original video from 2015: https://youtu.be/xsSnOQynTHs?t=615

  • Redux is called Redux because of Redux = (Red)ucer + Fl(ux) Why reducer is called reducer? Because Reducer reduces (state, action) into state.

  • Setup Development Environment

    • in webpack config (module: rules:) rules are processed “bottom-up” so the last one is first so ESLint is first and then Babel

    • ESLint: as VSCode extension, linting feedback is in the code; as Webpack module, it’s in console on build step In VSCode, Prettier overlaps with linters Prettier vs. Linters on Formatting rules, but not on Code-quality rules

    • Utilizes Auto Import extension in VSCode

  • Redux explained

    • Action Creator functions: actions are typically created by convenience functions that are called action creators. Typically, the action creator has the same name as the action’s type. Action creators are considered convenience functions because they’re not required, but I recommend following this simple convention.

    • Immutability;

      • Simple types in JavaScript are immutable already, such as numbers, string, Boolean, undefined, and null; every time you change the value of one of these types, a new copy is created. Mutable JS types are things like objects, arrays, and functions.
      • usually shallow copy; as a note, JS spread operator for objects {…b} makes shallow copies of those objects; if you need “deep” cloning, you have to clone nested objects too, ex. {…b, c: {…b.c}}, but do a “deep” clone only for nested objects if some value in them is changed; avoid blindly deep cloning - only clone sub-objects that are changed
      • with Immer you can write mutable code and it will clone in immutable manner behind the scenes (produce())
      • in Redux and JS, when managing arrays, avoid push, pop and reverse as they are all mutate an array, so you need to clone array before
      • How to enforce immutability? Immer does exactly that!
    • Reducers (must be pure functions) don’t-do’s:

      • you should never mutate arguments
      • you should never perform side effects, like API calls or routing transitions
      • and you should never call non-pure functions
    • If we have multiple reducers, which one is called when an action is dispatched? The answer is all of them. All reducers get called when an action is dispatched. The switch statement inside each reducer looks at the action type to determine if it has anything to do. This is why all reducers should return the untouched state as the default. NOTE: entire application really only has one single reducer function; read Reducer Logic )

  • Connecting Redux to React (via React-Redux); There are 2 core items:

    • Provider component; attaches app to store by wrapping everything; only once

    • and Connect function; wraps our component so it’s also connected to store; defines how we map and which part of redux state to our component props and how we map store actions as props to our component;

      • mapStateToProps; what state is exposed as props; being more specific is good for performance as component re-renders only when those props change; if you are using “expensive” changes in here, consider using Reselect library here as it will “cache” with “memoize” here; learn more on this
      • mapDispatchToProps; how to expose actions to components

With a plain basic Redux store, you can only do simple synchronous updates by dispatching an action. Middleware extend the store’s abilities, and let you write async logic that interacts with the store.

  • Redux middleware libraries for handling async:

    • redux-thunk; quite popular and was written by Dan Abramov who’s also the creator of Redux; easier to learn compared to redux-saga it’s extremly small, 10 lines? = it is a middleware that looks at every action that passes through the system, and if it’s a function, it calls that function. That’s all it does.
    • redux-promise,
    • redux-observable,
    • and redux-saga; really powerful, hard to learn and so extensive it needs separate course; uses JS generators are functions that can be paused and resumed later
  • for Snippets ni VSCode, he is using “react code snippets” extension

  • brzo idem od 06 - Redux

  • od 09 je uglavnom coding

  • Optimistic UI updates: interesting! We’ll assume the best; “delete” is good candidate

  • Testing Technologies

    • Testing framework: Jest (by Facebook), others: Mocha, Jasmine, Tape, AVA
    • Helper libraries: make testing easier; React Testing Library is lightweight and recommended by Facebook Enzyme (by Airbnb) or other: React Test Utils with too verbose API naming To be clear: Enzyme is using RTU behind the scenes with nicer API + JSDOM for in-memory DOM + Cheerio (for jQuery-like CSS selectors)
  • Testing React

    • Unit tests; Jest is main framework and Enzyme / RTL (React Testing Library) are testing utilities You can also use bahmutov/cypress-react-unit-test
    • E2E testing; Cypress is mostly used
  • VSCode extension snapshot-tools is handy for viewing Jest snapshots inline on hover

  • Jest snapshot files should be in git; we simply need a baseline for comparison when run in a fresh environment Official: the snapshot artifact should be committed alongside code changes, and reviewed as part of your code review process.

  • In Enzyme, console.log(wrapper.debug()); is very useful to see the rendered component and check what and why test selector is matching or not

  • React Testing Library

    • Unlike Enzyme, RTL doesn’t distinguish between shallow and mount. Components are always mounted (and its children are rendered)
    • debug output is nicely color-coded, unlike in Enzyme
  • Author favors React Testing Library, because of…?

  • Testing Redux;

    • he is explaining how to test every part of Redux, one by one: Connected components, Action Creators, Thunks, Reducers, the Store
    • when testing Redux Store, we are essentially doing integration tests, not unit tests
date 01. Jan 0001 | modified 28. May 2021
filename: Learn React » Course Notes » Pluralsight