The OZ Technical Guide to Getting the Most Out of Your React Code

Oz Digital Consulting Bnr-Tech-Guide

By Raza Ali

Download PDF

The React Javascript library can be a powerful tool for building effective user interfaces—but many developers only scratch the surface of its true power.

If that sounds like you, set your mind at ease: OZ has got you covered with the following insights.

Prelude: Functional vs Container Components

Stateless and stateful components are known by many different names: Container and presentational, for example. Or smart and dumb.

The main difference is that one has a state and the other doesn’t.

Stateless components—also known as functional components—are shorthand methods to create components that simply render something based on props passed to it and do not need to maintain state.

Using Functional Components

First, class components are almost deprecated as functional components are in demand and highly accepted as a good approach in react. In the future, the next versions will be enhanced with time.

Second, functional components are easier to read and test because they are plain JavaScript functions without lifecycle hooks.

Functional components get easier to separate container and presentational components because you need to think more about your component’s state if you don’t have access to setState () in your component.

There is one difference in the syntax: A functional component is just a plain JavaScript function that accepts props as an argument and returns a React element. A class component, on the other hand, forces you to extend from React and create a render function that returns a React element. This requires more code but will also give some benefits.

Stateful Component

A stateful component is always a class component. The stateful components are keeping track of changing data.

Stateful components should be used if you are…

  • …building an element that accepts user input or an element that is interactive on the page.
  • …dependent on the state for rendering—for example, fetching data before rendering.
  • …dependent on any data that cannot be passed down as props.

Stateless Components

Stateless components are also called presentational components or functional components. Components always render the same thing or only what is passed to them via props.

Stateless components should be used if you…

  • …simply need to present the props.
  • …don’t need a state or any internal variables.
  • …are creating non-interactive elements.
  • …want reusable code.

Compound Components

Compound components—or a pattern that encloses the state and behavior of a group of components while rendering control of its variable parts back to the external user—are used together to share an implicit state that lets them communicate in the background.

Separation of Concern

Having all the UI state logic in the parent component and communicating that internally to all the child components makes for a clear division of responsibility.

Reduced Complexity

As opposed to prop drilling to pass down properties to their specific components, child props go to their respective child components using the compound component pattern.

One major drawback of building components in React with the compound component pattern is that only direct children of the parent component will have access to the props, meaning we can’t wrap any of these components in another component.

The example code above is one of the implementations of compound components in which you get to see that the Menu, MenuButton, MenuList, MenuItem, and MenuLink were all imported from @reach/menu-button. As opposed to exporting a single component, ReachUI exports a parent component which is Menu accompanying its child’s components which are the MenuButton, MenuList, MenuItem, and the MenuLink.

When to Use Compound Components

As a React developer, you should make use of compound components when you want to:

  • Solve issues related to building reusable components.
  • Development of highly cohesive components with minimal coupling.
  • Better ways to share logic between components.

Conditional Rendering

In React, you can create distinct components that encapsulate the behavior you need. Then, you can render only some of them, depending on the state of your application. Conditions are the foremost tool in the arsenal of any software developer. In the process of writing React components, the need often arises to render a certain JSX code based on the state. This is achieved through conditional rendering.

How to write if…else in React

You can use variables to store elements. This can help you conditionally render a part of the component while the rest of the output doesn’t change. Consider these two new components representing the Logout and Login buttons. In the example below, we will create a stateful component called LoginControl.

Depending on its current state, it will render either <LoginButton /> or <LogoutButton />.

The Switch Statement

As shown previously, you can conditionally return different markup from a component based on set conditions using an if…else statement. The same could be achieved with a switch statement where you can specify the markup for various conditions.

Revise the LoginControl component and replace them if…else statement with a switch statement:

Inline If with Logical && Operator

It works because in JavaScript, true && expression always evaluates to expression, and false && expression always evaluates to false.

Therefore, if the condition is true, the element right after && will appear in the output.

Using Ternary Operators

Another method for conditionally rendering elements inline is to use the JavaScript conditional operator condition. true: false.

Render Props

Render props means that you pass a render function defined by a separate component’s props to indicate what should be returned by the shared component. At its root level, it must take the form. this.props.render() is a function passed in by another component.

This function itself should return a React component. The simple render prop we created above just wraps the element in a <div>. To utilize the <SharedComponent /> we would do the following:

Higher Order Components

A higher-order component (HOC) is an advanced technique in React for reusing component logic. HOCs are not part of the React API, per se. They are a pattern that emerges from React’s
compositional nature—a function that takes a component and returns a new component.

React’s Higher Order Component is a pattern that stems from React’s nature that privileges composition over inheritance.

In the above example, higherOrderComponent is a function that takes a component called WrappedComponent as an argument. We have created a new component called HOC which returns the <WrappedComponent/> from its render function.

While this adds no functionality, it depicts the common pattern that every HOC function will follow.

We can invoke the HOC as follows:

A higher-order component transforms one component into another component.

Note that a HOC doesn’t modify the input component. Rather, a HOC composes the original component by wrapping it in a container component.

State Hoisting

One of the React patterns is called state hoisting. As we know stateless functions don’t hold state and events are state changes. The data needs to be passed to stateful container component parents. This is a perfect situation to use state hoisting and it’s accomplished by passing a callback from a container component to a child component.

In this example above the state is hoisted to the container, by the provided callback. This sets a clear boundary and makes it easy to have re-usability of stateless function.

Another example is the use of the Controlled input pattern.

Let’s create a controlled input:

Provider Pattern

According to React docs, “Context provides a way to pass data through the component tree without having to pass props down manually at every level.”

This means Context API helps us skip the mandatory hierarchy of passing props for each component in its tree.

The provider pattern, however, is not only about React context. You might have used a state management library like redux and mob. Here provider is the top component and it is provided by react-redux. We write it the following way:

React-redux has implemented the provider pattern where the provider component receives the state as props and each child component has implicit access to the managed state.

 

Regardless of where you are on your digital transformation journey, OZ experts will put our twenty-five years of experience to work for your organization, helping you to streamline processes, save money, increase scalability, gain competitive advantage, and improve business efficiency and operations. Find out more about our services here