About Me
Blog

Intro To React: Part 1

React From First Principles

November 30, 2020

4 min read


React is a JavaScript library for creating interactive UIs that is all the rage right now. However too often beginners dive straight into React and treat what they’ve learnt as “React magic”. I want to take a different approach - by building up React from a set of good solid fundamentals.

I’m trying a new scrollytelling style for this blog post - let me know on Twitter if you liked this style.

if (props.innerText) {
<div id="root" />
<script>
document.getElementById("root").innerHTML =
"<div><h1> Hello World </h1> <p> Other text </div>"
"<div><h1> Hello World </h1> <p> Other text </p></div>"
</script>
if (props.innerText) {
<h1> Hello World </h1> <p> Other text </p>
"<div><h1> Hello World </h1> <p> Other text </div>"
if (props.innerText) {
<h1> Hello World </h1> <p> Other text </p>
if (props.innerText) {
React.createElement("h1", null, " Hello World "),
<h1> Hello World </h1> <p> Other text </p>
if (props.innerText) {
<h1> Hello World </h1> <p> Other text </p>
React.createElement("h1", null, " Hello World "),
if (props.innerText) {
<h1> Hello World </h1> <p> Other text </p>
ReactDOM.render(<App />, document.getElementById("root"))
if (props.innerText) {
ReactDOM.render(App(), document.getElementById("root"))
ReactDOM.render(<App />, document.getElementById("root"))
if (props.innerText) {
<h1> Hello World </h1> <p> Other text </p>
ReactDOM.render(App(), document.getElementById("root"))
if (props.innerText) {
<h1> Hello World </h1> <p> Other text </p>
if (props.innerText) {
<h1> Hello World </h1> <p> Other text </p>
ReactDOM.render(<App />, document.getElementById("root"))
if (props.innerText) {
<Button innerText="I do nothing" onClick={() => {}} />
ReactDOM.render(<App />, document.getElementById("root"))
if (props.innerText) {
<Button innerText="I do nothing" onClick={() => {}} />
ReactDOM.render(<App />, document.getElementById("root"))
if (props.innerText) {
<button onClick={props.onClick}>{props.innerText} </button>
ReactDOM.render(<App />, document.getElementById("root"))
if (props.innerText) {
return <button onClick={props.onClick}>{props.innerText}</button>
<button onClick={props.onClick}>{props.innerText} </button>
if (props.innerText) {
return <button onClick={props.onClick}>{props.innerText}</button>

Vanilla JS and the DOM

The vanilla JS approach to adding interactivity to a website is by directly manipulating the DOM, using the special document object. We query specific DOM elements by tagging that element in some way (e.g through an id or through a CSS class).

The document object is quite barebones and error-prone. For one, it is on us to correctly close tags in HTML strings. If we miss out a </p> tag, as we do here, we won’t get an error until runtime.

It’s also a lot of boilerplate to write the querying logic and tag our elements accordingly.

Really, we want a library to abstract away the messy nature of the document API for us. This is where React comes in.

Enter React

React abstracts this DOM manipulation away by introducing a virtual DOM (ReactDOM). We now manipulate React elements in the virtual DOM, and let React handle changes to the actual DOM. All we need to specify is the DOM node into which we hook our ReactDOM into - here it’s the root div. From now on, say bye to document!

JSX

React elements are written with JSX syntax (this is just like writing HTML in JS), with the added perk of React checking that we close our tags correctly!

This is syntactic sugar for a set of createElement calls to update the virtual ReactDOM. This abstraction is handled by Babel, a JavaScript compiler that usually comes pre-bundled with React frameworks like Create React App.

It might appear that we haven’t gained much from writing React JSX compared to HTML, as we’ve effectively written the same code.

However, using a virtual DOM means React can introduce abstractions that aren’t present in the actual DOM and then translate those under the hood to actual DOM operations.

Components

Say we want to reuse parts of the DOM to avoid duplicating code. How would we reuse duplicate JS code? Functions. And that’s all components in React are. Functions that return React elements.

Again, this JSX tag syntax for <App/> is just syntactic sugar. You could equivalently write it with normal function syntax (App()).

And like you can call functions in multiple places in the code, you can reuse this App component.

Sidenote: <> is shorthand for <React.Fragment>, and you can use it to indicate to React virtual DOM that you want to return a group of elements. Wrapping with <> </> doesn’t actually add any elements to the actual DOM! This is a perk of the virtual DOM, with the actual DOM we’d have to unnecessarily wrap groups with a <div>.

Just as we can call functions within each other, we can nest components within another.

Components can take arguments too: this JSX syntax looks a lot like HTML attributes! We wrap JS expressions in {}, but this is nothing specific to React, it’s just like template strings in vanilla JS: 'This is ${1 + 2}'.

Props

But really this JSX syntax for component attributes is syntactic sugar for a function call with a single object passed in as an argument. React has a special name for this object: props (short for properties) and its fields are the properties we specify in the tag.

We can access the values of fields inside our component function by doing props.___.

We can use these props to render different versions of our component, for example depending on whether we pass the argument props.innerText. So every times the props change, React will re-render the component. Since props is used by React to determine whether to re-render a component, it is immutable. This is to make sure the component is pure - given the same props as arguments, it will produce the same rendered output.

You might think this re-rendering is expensive, but this is a re-rendering of the virtual DOM. React’s reconciler does a diff to figure out what has changed, and then only updates the parts of the actual DOM that have changed.

The benefits of React

We’ve just outlined the core of React in this blog post. It’s worth taking a step back and highlighting the key advantages of React:

  • No mutation or side effects
  • Local knowledge of components
  • Separates view and application logic

If we look back at the DOM document API we were using, to update our DOM we had to directly mutate elements the elements, often as side-effects of clicking a button. The issue here is that there’s an implicit state in the DOM that we as developers have to track - which event listeners can mutate this part of the DOM as a side-effect, which order they mutate it etc.

With React, the state a component requires is made explicit with the props object. The only way to change the rendered output of a component is by passing different props - there are no side-effects. Within the component itself you don’t have to worry about mutations as the props are treated as immutable and React will re-render whenever they change. This way you can leave the setting of the props to the application logic, and the rendering of the components to your React logic.

Props also act as a good abstraction boundary for local reasoning. When using a component, you don’t need to know the internals, as the output is solely dependent on the props you pass in, and as mentioned, within the component you don’t have to worry about how it will be used.

We’ve only just got started with React, in the next post I’d like to look at Hooks from this same foundational perspective. If that’s something that interests you, either follow me on Twitter or sign up via email to be notified when the next post is coming out!

Join my newsletter for more content like this!

Email subscribers get exclusive access to the latest posts first!

Share This On Twitter

If you liked this post, please consider sharing it with your network. If you have any questions, tweet away and I’ll answer :) I also tweet when new posts drop!

PS: I also share helpful tips and links as I'm learning - so you get them well before they make their way into a post!

© Mukul Rathi 2021