The Talent500 Blog
Essential React design patterns for developers 1

Essential React design patterns for developers

React has kept its spot of being the most widely used JavaScript framework since its inception. It is used on 24% of the entire internet, making it a great JavaScript library to master. As a front-end developer, you must keep up with the evolution of technologies, but React is a framework that keeps steady with its reusable components. Learning React.js will benefit your career as it is there to stay.

Facebook, the creator of React, actively develops and maintains the library giving it the much-needed edge over other frameworks and libraries. React can use the design patterns to offer a robust development environment compared to other JavaScript libraries.

The importance of React design patterns 

Design patterns are essential concepts of project development. React and every other programming language has some design patterns that help prevent the commonly occurring problems in software development.

In simpler terms, React design patterns are the basic templates upon which you can build a program’s functionality according to the given requirements. Developers who understand design patterns can speed up the development process. Also, such software engineers will be able to write easier-to-read and maintain code.

This article will cover some basic React design patterns that developers must know.

The HOC (Higher Order Component) Pattern

When creating Reactive applications, you often have to use the same logic in various modules—for instance, using the same design elements for different Card Views or third-party subscription data components in the interface design.

Higher-order components are a popular React design pattern for creating logic shared between various components. With the HOC pattern, you don’t have to rewrite the code; you can extend the existing code’s functionality. HOC functions are considered pure functions as they do not have any side effects on the quality of the code.

A HOC function is a JavaScript function that takes a component as an argument and returns another component by adding additional data to the Component. This functionality is inherent to React as the programming language prefers composition over inheritance. Here’s an example of a HOC React design pattern:

import React, { Component } from “react”;

const higherOrderComponent = (DecoratedComponent) => {

  class HOC extends Component {

   render() {

    return <DecoratedComponent />;

   }

  }

  return HOC;

};

Many popular React frameworks use this design pattern, most notably Redux’s connection function. If your project is based on React or Redux, you can use a higher-order component design pattern to simplify your code and make it more maintainable.

React Hooks design patterns

Hooks were introduced in React version 16.8, and they revolutionized how developers build React components. The React Hook API lets components access the most commonly used React features like state, props, context, refs, and lifecycle. When you use the React Hook design pattern, you increase the potential of functional components as they are now as powerful as the class components.

A React Hook design pattern might seem similar to a Presentational and Container Components design pattern, but there’s a difference. 

Presentational and Container Component design patterns usually create massive logic split across different lifecycle methods. Such components are hard to read and maintain. React Hooks make functional components highly robust, and they can perform all the functions of containers but without their limitations.

Here’s an example of a container method:

import React, { Component } from “react”;

class Profile extends Component {

constructor(props) {

   super(props);

   this.state = {

    loading: false,

    user: {},

   };

  }

componentDidMount() {

  this.subscribeToOnlineStatus(this.props.id);

  this.updateProfile(this.props.id);

  }

componentDidUpdate(prevProps) {

   // compariation hell.

   if (prevProps.id !== this.props.id) {

   this.updateProfile(this.props.id);

   }

  }

componentWillUnmount() {

this.unSubscribeToOnlineStatus(this.props.id);

  }

subscribeToOnlineStatus() {

   // subscribe logic

  }

unSubscribeToOnlineStatus() {

   // unscubscribe logic

  }

  fetchUser(id) {

   // fetch users logic here

  }

  async updateProfile(id) {

   this.setState({ loading: true });

   // fetch users data

   await this.fetchUser(id);

   this.setState({ loading: false });

  }

  render() {

   // … some jsx

  }

}

export default Profile;

The code is not optimal. The setState() can only change the first level of any state object. Also, the inline action methods like the onHandleChange() increase the line of code. Related logic is repeated multiple times.

The same code using React hooks design pattern:

import React, { useState, useEffect } from “react”;

function Profile({ id }) {

  const [loading, setLoading] = useState(false);

  const [user, setUser] = useState({});

// Similar to componentDidMount and componentDidUpdate:

  useEffect(() => {

  updateProfile(id);

  subscribeToOnlineStatus(id);

   return () => {

   unSubscribeToOnlineStatus(id);

   };

  }, [id]);

 const subscribeToOnlineStatus = () => {

   // subscribe logic

  };

const unSubscribeToOnlineStatus = () => {

   // unsubscribe logic

  };

const fetchUser = (id) => {

   // fetch user logic here

  };

const updateProfile = async (id) => {

  setLoading(true);

   // fetch user data

   await fetchUser(id);

  setLoading(false);

  };

return; // … jsx logic

}

export default Profile;

Now you have direct access to the state of objects, and functional components can also use state. The useEffect method replaces lifecycle methods like componentDidMount and componentWillInmount, making code cleaner and concise.

Conclusion 

React design patterns can give you access to fantastic programming language features to create scalable, secure, and robust React apps. The above two React design patterns are generally used to write clean and maintainable React code. Also, don’t miss our React developer toolkit that lists additional resources React developers can use to upskill.

Talent500 is a platform for React developers to find opportunities at global companies. Join our elite pool of talent to get discovered by international companies. Sign up here.

 

 

0
Manik Sharma

Manik Sharma

Manik Sharma specializes primarily in UI or Software Development using Javascript libraries like React and Redux along with HTML, CSS, and other libraries like Bootstrap, Node.js, Express.js, MongoDB. He loves to talk business and think of cool startup ideas. Definitely, an entrepreneur in making. He is equally interested in discussing innovative ideas that can make a huge difference in someone's life.

Add comment