Code With Mosh
Mastering React
A few key concepts from Code With Mosh’s Mastering React course
Some background on myself
Before taking the course, I had around 9 months experience building applications using js, jquery & php. After hearing a lot of great things about React, I thought I would give it a go!
Code With Mosh
Firstly, I cannot recommend codewithmosh tutorials highly enough. He is a clear teacher who moves at a great pace preventing you from ever getting bored — having now taught over three million people I know I am not the only person who feels this way.
Getting Started
So what is React?
Created (in 2011) and maintained by Facebook, React is a “Javascript library for building user interfaces”. It has become the most popular library in this space beating alternatives such as Vue and Angular.
A React application is comprised of a tree of individual & re-useable components which are compiled to create complex user interfaces. For example, Twitter (a React application) can be thought to be comprised of a Navbar component, profile component, feed component ….
A component is comprised of a class, a state (responsible for the data) and a render function which returns a react component.
The really smart thing
React keeps a lightweight version of the DOM in memory which can be referred to as the virtual DOM. When a state of a component is changed we get a new react element. React will then compare this element and its children with the previous element, figure out what has changed and then only what has changed in the real DOM — it is “Reactive”.
Unlike JQuery, when working with React we never manipulative the real DOM itself. Instead, we simply update States and let React perform the updates automatically!
What is JSX?
JSX stands for JavaScript XML and is used by most React developers to write HTML to be rendered. At runtime, a compiler (in our case Babel) is used to translate JSX into regular JavaScript to be run in a browser.
ES6 Refreshed
What is ES6?
Before this tutorial, I had not really used ES6 so it was great to have this refreshed.
ES6 was published in June 2015 and is version 6 of the ECMA Script programming language. In summary, ES6 is a major update to JavaScript that includes loads of new great features.
Variables Types
Before ES6, we just had the var keyword when declaring variables. ES6 introduces the let and const ways of declaring variables.
- let — this is used when you want the ability to reassign the identifier. It is only accessible within the block (block-scoped) of the function that it is defined in and not openly in the entire function itself.
- const — this is used when the identifier can’t be reassigned. It is similar to let in terms of how it is only accessible within the block it is defined in.
- var —similar to let in the sense that is can be reassigned but different as it can be accessed throughout the entire function. It is therefore the least strict of variable types.
Arrow/Map/Spread
Arrow functions (new to ES6) provide a cleaner way to define and write functions.
The map() method creates a new array populated with the result of calling a given function of every element of a provided array.
Finally, the spread syntax can be used to clone an array ([…array]) or concatenating two arrays ([…array1,…array 2]).
Object Destructing
Object Destructing allows you to extract data from arrays, objects, maps and sets and write way cleaner code. Instead of having to declare variables using a lot of repetition (lines 7–9), you can define all three constants in one single line (line 11)!
Components + Composing Components
Extensions
Before getting into writing code, we installed a couple of extensions which proved invaluable:
- simplereactsnippets — a collection of constantly used react snippets which saves a lot of time and prevents stupid errors. The quick commands I used the most were imrc (import react and components), ccc (creates react class), sfc (creates stateless function component).
- prettier — a code formatter which properly formats you code whenever you save
What is a component?
A component is an independent and reusable piece of code which can come as either a Class component or Function component. A component accepts inputs and then returns a React element.
States & Props
React components have a built-in state object which can be used to store properties that belong to that object. What the state is changed, the component re-renders. As we can see in the example below, you can retrieve data within the State (sending a request for example) and then use this data within your component.
A component can also get data via Props which are passed to a component via its parent.
So what is the difference? Props are read-only and cannot be modified which states are owned by the component can be modified using this.setState. If you change the state using this.setState() then React will now know to re-render the component based on this new state.
Setting a State
In React you cannot directly change a state. Instead you must use the setState() method in which you pass an object which either overrides or adds a new value to the component state. As we can see in the example below, when we are clicking the increment button we are adding 1 to the count value with the component’s state with React then handling the rest!
Lifting the State Up / Single Source of Truth
As explained initially, a React application is comprised as a tree of components. Let’s say that you have a component which is a count of the rows of the table (“this table contains 9 rows”) and a second component which generates the table itself. These components could get there data from their own states as mentioned above this would mean that this data is local to the component.
This can lead to issues as you cannot guarantee a single source of truth — as both of these components are using the same source of data they should both inherit this data from a parent component which stores the data once in its own state! This means that if one component triggers a change in state of the master data all of the components will automatically get rendered taking this change into account — got to love React!
However, we now have a problem. As the state is local to its component (in this case the parent component), we can no longer change the state from the table component or kpi component. We must pass the change we want to make up the tree to the parent and allow this change to happen in a parent function!
The child will raise the event and the parent will handle the event.
To do this we need to do two things:
- Pass the function from the parent to the child. In the example below we are passing the handleDelete function downwards.
- Access this onDelete function from the component’s own properties.
Life-cycle Hooks
A React component goes through certain phases in its life with the three core life-cycle's being:
- Mount: When a component is created and sent to the DOM. Common methods include render and componentDidMount.
- Update: When a component updates. Common methods include render and componentDidUpdate.
- Unmount: When a component is removed from the DOM.
Pagination
React applications are Single Page Applications or SPA’s. However, it is common to want to create multi-page applications which is where the Router module comes in with this module easily allowing you to create a multi-page app.
Clear and basic example: https://reacttraining.com/react-router/web/example/basic
In essence, when you click a link to a new path you simply define to=<a given path> for example <li> <Link to=”/about”>Home</Link></li>. You then set a route <Route path=”/about”><About /></Route> which says that if the path is “/about” render the About component — it’s that simple.