My FeedDiscussionsHeadless CMS
New
Sign in
Log inSign up
Learn more about Hashnode Headless CMSHashnode Headless CMS
Collaborate seamlessly with Hashnode Headless CMS for Enterprise.
Upgrade ✨Learn more
8 Irrevocable Laws of React.js you must know

8 Irrevocable Laws of React.js you must know

Destiny Ajakaiye's photo
Destiny Ajakaiye
·May 11, 2020

Introduction

In this post, I'm going to abstract the ideology of laws to explain the basic concepts in React.js. When I first started learning React.js about a year ago I struggled to understand the whole idea of React, how it works, its ecosystem, and all of the good stuff that comes with the framework. Do you know why I struggled?

Each and every time we learn something new our brain forms new connections and neurons and makes existing neural pathways stronger or weaker. This change is known as plasticity in the brain. Everything you learn goes first to your short term memory, and some of it transfers later to long term storage in your brain. The quickest way to understanding concepts and have them transferred to your long term memory is by applying what is called Mental Models.

A mental model is an explanation of someone's thought process about how something works in the real world. It is a representation of the surrounding world, the relationships between its various parts, and a person's intuitive perception about his or her own acts and their consequences. One of the many ways of applying mental models is by using laws.

According to the dictionary meaning, laws are systems of rules which a particular country or community recognizes as regulating the actions of its members and which it may enforce by the imposition of penalties. Laws paint the representation of a concept and its relationship to the real world in our brain which then causes us to act on those laws.

From my experience working with React.js and with the guidelines on the official documentation of the framework, I have put together some important laws to remember when working with React.js, they will also help you understand the concepts behind them (laws) and how to implement them correctly.

Shall we begin?

1. The Law of Props Mutation

This law states that props are read-only.

Props are properties of a component and its a way of passing data from a parent component to a child component. Whether you declare a component as a function or a class, it must never modify its own props. Consider the code below:

const Button = ({ title }) => { 
    return (
        <button type="button">{title}</button>
    );
}

The above code snippet refers to has pure component because it's not attempting to change the props passed to it, but always returns the same result. Let's consider another example:

const Button = props => { 
    props.title = "Create";
    return (
        <button type="button">{props.title}</button>
    );
}

This is wrong because here we are trying to mutate(change) the props passed to the Button component.

2. The Law of Immutability

This law states that you should never mutate the state property of a component directly, but only through the setState() method.

States are similar to props, but they are private and fully controlled by their components respectively.

For example, the code below will not render a component because it is violating the law.

//wrong
this.state.name = "Destiny Ajax";

But this will:

//correct
this.setState({
  name: "Destiny Ajax"
});

3. The Law of Rendering Elements

This law states that when rendering more than one element, you must wrap them inside a single parent element.

The code below will result to an error.

const elements = (
    <h1>Header 1</h1>
    <h2>Header 2</h2>
    <p>Paragraph</p>
);

Instead all elements are suppose to be wrap in a parent element like a div or a Fragment.

const elements = (
    <div>
        <h1>Header 1</h1>
        <h2>Header 2</h2>
        <p>Paragraph</p>
    </div>  
);

Note: React elements are immutable. Once you create an element, you can’t change its children or attributes. Learn more.

4. The Law of Component Naming

This law states that if you are rendering your component using JSX, the name of that component has to begin with a capital letter.

React treats components starting with lowercase letters as DOM tags. For example, <div /> represents an HTML div tag, but <Welcome /> represents a component and requires Welcome to be in scope. The code below will throw an error during compilation.

<MyComponent>
    {/* this is so wrong */}
    <app name="My App" />
</MyComponent>

Rather it should be like this instead:

<MyComponent>
    {/* this is the right way */}
    <App name="My App" />
</MyComponent>

Note: Only HTML elements and SVG tags can begin with a lowercase. Hence, <div /> is okay but <app> is not.

5. The Law of Composing Components

This law states that components can refer to other components in their output.

When building applications with React you are advised to break down the whole application into atoms of components. Just like legos, each component is a building block of the entire application piece by piece and this is exactly what this law is stating. Take a look at the code snippet below:

const elements = (
    <div>
        <UserInfo name="Destiny Ajax" />
        <Avatar />
        <SearchBar />
    </div>  
);

You can create components and reuse them across the entire application.

6. The Law of Unidirectional Data Flow

This law states that a state is always owned by one Component. Any data that’s affected by this state can only affect Components below it(its children).

Changing the state on a Component will never affect its parent, or its siblings, or any other Component in the application: just its children.

Because of this singular reason, if two components need to share state the state needs to be moved up to a common ancestor. Consider the example below:

class TimerApp extends React.Component {
    state = { 
        counter: 0
    };

    render() {
      return (
        <div>
          <Display counter={this.state.counter} />
          <CounterEngine counter={this.state.counter} />
        </div>
      )
    }
}

7. The Law of using Indexes in Key Prop

This law states that when iterating over a collection of elements, each element should be uniquely identified in the DOM using the key prop.

Keys help React identify which items have changed, are added, or are removed. Keys should be given to the elements inside the array to give the elements a stable identity.

Keys help React to easily reconcile the differences between the virtual DOM and the real DOM. Personally, when iterating over a collection of items I usually use indexes from the array as value to the key but this is officially regarded as bad practice in the React community.

{elements.map((element, index) => 
    <CardList {...element} key={index} />
)}

The implementation above is regarded as bad practice and should not be used in large applications. Reason is, keys should be stable, predictable, and unique so that React can keep track of elements but unfortunately for some of us indexes are actually unique but not predictable so we can't rely on them.

8. The Law of Lifecycle Events

This law states that during the lifetime of a component, there’s a series of events that gets called, and to each event, you can hook and provide custom functionality.

In React, class components can have hooks for several lifecycle events. These hooks or methods as they are often referred to get called when different events occur in the component. There are 3 phases in a React component lifecycle:

  • Mounting
  • Updating
  • Unmounting

Mounting

When mounting you have 4 lifecycle methods before the component is mounted in the DOM: constructor, getDerivedStateFromProps, render and componentDidMount.

Updating

When updating you have 5 lifecycle methods before the component is mounted in the DOM: the getDerivedStateFromProps, shouldComponentUpdate, render, getSnapshotBeforeUpdate and componentDidUpdate.

Unmounting

Lastly, this phase we only have on the lifecycle method which is the ComponentWillUnmount.

For a broader understanding of the functions of these lifecycle methods visit the official docs.

Conclusion

So far we have been able to explain these few but important concepts in React.js by viewing them as laws. If you spend time practicing these laws it will help your understanding about them and how to implement them in your applications. Please note that the concepts explained in the article are basic and fundamental concepts every React developer should know and I tried to explain them based on my own understanding and experience working with React.

If you feel there's something I missed out that is supposed to be in this article please use the comment section to list them so that others can learn too. I hope this gives you a bit of a head start with understanding these fundamental concepts in React.js.

Thanks for reading!