Photo by Artem Sapegin

What is React?

React is a flexible Javascript library created by Facebook in 2011 that handles the View in traditional MVC model apps. React lets you create highly efficient and reusable UI’s known as components that encapsulate logic in its own state. This is why React is awesome at rendering, making it easier and faster. But we’ll get into components a little later.

Declarative vs Imperative

React is a declarative language, meaning we describe how components will look and interact and React takes care of the how, and translates our declarative code to the browser.

Other Imperative languages need to be told how the data will be controlled and flow. Both present their strengths and weaknesses, however letting React do all the work is a better approach for web development.

Here’s an example:

Imperative programming is like asking someone to paint a wall in a room, and a micromanager giving the employee giving step-by-step instructions on how the wall should be painted. 

Declarative programming is like giving someone the same tools to paint the wall. You don’t necessarily care how the wall gets painted, as long as it is done.

Photo By: https://www.advantexe.com/blog/how-to-effectively-work-with-a-micromanager

Photo By: https://i.pinimg.com/originals/14/47/ad/1447ad3649aa276dede6fee3d91ea785.jpg

React does just this, you describe what the UI will look like and it will take care of the how.

Some Code …

Ok, for those of you who like to jump straight to the code – this is an example of what changing a text color would look like in React vs plain Javascript. 

Javascript:


const p = document.createElement("p");
p.className = "example red";
p.onClick = function(event){
 if(this.classList.contains('red')){
  this.classList.remove('red');
  this.classList.add('blue');
 }
else{
  this.classList.remove('blue');
  this.classList.add('red');
 }
}
  

 

In the above sample, we are manipulating the DOM and recalculating the UI if the function returns true. Although this is a basic example, direct DOM manipulation would cause an update on the element and its children. The re-rendering on the UI could be expensive to the DOM if there are multiple children elements, causing the UI to be slow for every update.

 


export default class Form extends React.Component {
    constructor(props) {
        super(props);
        this.state = ({
            color: "red"
        })
    }
    handleColor() {
        if (this.state.color == "red"){
            this.setState({ color: "blue" });
        }
        else{
            this.setState({ color: "red" });
        }
    }

    render() {
        return (
            <div>
                <button onClick={this.handleColor.bind(this)}>Change Color </button>
                <p style={{ color: this.state.color }}>I'm {this.state.color}!</p>
            </div>
        )
    }
}

 

In this second example, we see that React doesn’t access the DOM directly. Instead, it knows it should render an element based on a current state. it determines if a change is necessary and makes the best calculation in updating with the fewest amount of steps. Which brings us to our next topic: React’s Virtual DOM.

Virtual DOM

React uses a Virtual DOM where a copy of the real DOM is kept in memory. If there is a change in the state, a new virtual DOM is created and compared with the previous virtual DOM tree. If a node in the DOM tree is different, or “dirty”, the Virtual DOM will calculate the best method to make the change to the real DOM.

Once React finds the nodes needing to be updated, it will only update the affected objects in the real DOM (in batches). By doing this, it ensures that the minimal steps are taken to update the real DOM and makes the performance much faster.

Photo source: https://www.oreilly.com/library/view/learning-react-native/9781491929049/ch02.html 

Bottom Line: You create a state of what the object should look like in the UI and let React do the magic of updating ONLY the changes that have been made to the real DOM.

 

More complex magic happens under the hood, but for now this best summarizes the advantages of the Virtual DOM.

Components

As promised, this will be a super simple explanation of React components. Components let you split the UI into independent and reusable pieces that are isolated. Think of components like Lego blocks that we can piece together to build something awesome.

Components accept properties (props) that return a React element that describes what the UI should look like.

class MyComponent extends React.Component {
     render() {
         return <div> Greetings from React component </div>
     }
 }

 class ParentComponent extends React.Component {
     render() {
         return (
             <div>
                 <MyComponent />
             </div>
         )
     }
 }

The need to know …

Components should always start with a capital letter. This way, React knows the difference between the native HTML tags and custom components like MyComponent.

 

So now, we’re all caught up with the basic understanding of components.

Components can talk to each other by sharing properties with one another called props, which you may have seen earlier.

Props

Props are how components share data with one another in a downward directional flow from parent to child. Props that are read in a child are immutable (can’t be changed) and can only be updated in their parent’s component through callbacks.

The child component can access a prop through this.props.

You can see in the code snippet below, we are passing the property of greeting to the child component MyComponent.

class MyComponent extends React.Component{
    render() {
        return <div>{this.props.greeting} from React Parent </div>
    }
}

class ParentComponent extends React.Component{
    render() {
        return (
            <div>
                <MyComponent greeting={"Hi!"} />
            </div>
        )
    }
}

Props are what make components so easy to be reused. So where do we set props, and what if they need user input? Glad you asked … that’s where use of a local state comes into play.

State

A component state is completely different from props because they are mutable (can be changed). A state is used to keep track of a component’s data and is entirely encapsulated within the component, meaning only that component can update its state through the setState function.

Using the setState function triggers a re-render, as we learned in the virtual DOM explanation, causing that component and child components to redraw the UI.

Components with a state, as shown in the example below, are known as stateful components, while simple components without a state are called stateless components.

Easy stuff, right?

 

export default class Form extends React.Component {
    constructor(props) {
        super(props)
        this.state = {
            name: "",
            city: "",
            state: ""
        }
    }
    handleName(value) {
        this.setState({ name: value });
    }
    handleCity(value) {
        this.setState({ city: value });
    }
    handleState(value) {
        this.setState({ state: value });
    }
    render() {
        return (
            <div>
                <div>
                    <FormResponse {...this.state} />
                </div>
                <form>
                    <label>Name: </label>
                    <TextInput 
                        onChange={(e) => { this.handleName.bind(e.target.value) }} 
                        value = {this.state.name}
                    />
                  
                    <label>City: </label>
                    <TextInput 
                        onChange={(e) => { this.handleCity.bind(e.target.value) }} 
                        value = {this.state.city}
                    />
          
                   <label>State: </label>
                   <TextInput 
                       onChange={(e) => { this.handleState.bind(e.target.value) }} 
                       value = {this.state.state} 
                   />
               </form>
            </div>
        )
    }
}

class FormResponse extends React.Component {
    render() {
        return (
            <div>
                <h1>Hi {this.props.name}, from {this.props.city},
                <span style={{ textTransform: "capitalize" }}>{this.props.state}</span>
                </h1>
            </div>
        )
    }
}

In the above snippet, you can see we have a few items in the state waiting for user input. On each key entry, we are calling the appropriate function that sets the state to its value.

Each time the setState function is called, React knows something has changed and triggers a re-render for the component and its child.

What’s with …?

The … operator is know as the spread operator that lets you pass all the objects in properties instead of defining them like we did in the previous examples. It’s a Javascript thing … super cool, huh?

Now that we’ve covered components, props, state, virtual DOM and more, we’re off to a great start building React Apps. I hope this was a good article to help you understand and get more familiar with React.

If you’d like to keep up with more of our designer and developer insights, follow us on Twitter to get notified of new posts.