×
iFour Logo

A comprehensive guide on advanced React Component Patterns

Rajal Parmar - September 20, 2021

Listening is fun too.

Straighten your back and cherish with coffee - PLAY !

Sustainable

What are React Patterns?

React Patterns means how react handle the flow of code, which type of criteria it followed and how to manage whole things, it’s all about its workflow life cycle.

Component patterns in react

Higher-Order Component

Once you create one component and that code will be used in your entire project more than one time that time you take the component as HO, C first you create a component in your project you can use multiple times in your project, that is a benefit you do not have to write a code more and more time its increase the higher performance of React its also increase the readability of React.

Example:


import React from 'react';// Take in a component as argument WrappedComponentconst higherOrderComponent = (WrappedComponent) => {// And return another component
  class HOC extends React.Component {
    render() {
      return <wrappedcomponent />;
    }
  }
  return HOC;};

				

Passing props:

React is unidirectional it decreases the complexity of code it makes it easier for developers. Data are passed from parent component to child components and the entire process of the props will be immutable it's just getting the direction from parent to a child not change the props value.

Reused Component: react is component-based, in react you can read any component in the other component its also increase the readability of React.

Spread and Rest operators :

The spread operator allows you to get elements out of an array (=> split the array into a list of its elements) or get the data out of an object.

Spread: used to split up array element or object properties:

Rest: used to merge a list of function arguments into an Array

Destructuring:

Array Destructing: easily extract array elements and store them in a variable.


[a,b] = [ &amp;lsquo;add&amp;rsquo; , &amp;rsquo;sub&amp;rsquo;]
Console.log (a ); 
// Print &amp;ldquo;add&amp;rdquo;
Console.log (b );
//print  &amp;ldquo;sub&amp;rdquo;
Object Destructing:easily extract object element and strore them in variable.
{name}  =  {  name: &amp;rsquo;max&amp;rsquo; , age:29 }
Console.log(name);
//print  max
Console.log(age);
//print  undefined 

				
 

Conditioal Rendering

If-Else Condition operator :


if(a&gt;b)
  {
     console.log(a);
}
else 
{
  console.log(b);
}

				

Ternary operator :


  render() {
    return (<div>
        <warningbanner warn="{this.state.showWarning}" /><button onclick="{this.handleToggleClick}">
          {this.state.showWarning ? &amp;#39;Hide&amp;#39; : &amp;#39;Show&amp;#39;}</button></div>
    );
  }

				

Array and list:


function NumberList(props) {
  const numbers = props.numbers;
  const listItems = numbers.map((number) =&gt;<li>{number}</li>
  );
  return (<ul><li>{listItems}</li></ul>
  );
}
 
const numbers = [1, 34, 3, 4, 52];
ReactDOM.render(
  <numberlist numbers="{numbers}" />,
  document.getElementById(&amp;#39;root&amp;#39;)
);

				

Keys: is a uniquely identify the rows which data is deleted updated that time it's useful for apply unique id.


const numbers = [1, 34, 3, 4, 52];
const listItems = numbers.map((number) =&gt;<li key="{number.toString()}">
    {number}</li>
);

				
contextAPI
[contextAPI]

Create the Provider

First, we have to create a provider which is defined in syntax and pass the value in the value tag after creating the provider you have to create a consumer and initialize and create the consumer creation. Which define all syntax in the below code and consider the one example you getting more easily thorough this code

<mycontext.provider value="{"></mycontext.provider>
				

Create the consumer

 &lt; MyContext.Consumer&gt;
  {value =&gt; / create context value/}

				

Initializing Content:


export const ThemeContext = React.createContext({  theme: themes.dark,  toggleTheme: () =&gt; {},});

				

Consumer Creation:


function Layout() {
    return (<div>      <sidebar />      <content /></div>
    );}
  // A component may consume multiple contextsfunction Content() {
    return (    <themecontext.consumer>    
    {theme =&gt; (        <usercontext.consumer>       
     {user =&gt; (            <profilepage theme="{theme}" user="{user}" />        
    )}        </usercontext.consumer>      )}   
   </themecontext.consumer>  );}
   

				

Looking to Hire React Developers ?
Your Search ends here.

 

Layout component: Layout Component work like that

As its name states - it defines the layout of the application. It simply accepts children as props and renders them to the DOM together or without other child components.


import React from &amp;#39;react&amp;#39;;
const Layout =({children}) =&gt;{
    return(
        &lt;&gt;<div>
            <toolbar />
            <sides />
            <backdrop /></div>
<main>{children}</main>
        &lt;/&gt;
    )}
export default Layout;

				

Hooks Component:

Hooks and their advanced features are established in ES6. Using the hooks component, we can set the state in the function component. We can even use componentDidMount and componentUnmount with hooks components to pass the context.

UseState:

It is a Hook (function) that allows you to have state variables in functional components.

Example:


import React, { useState } from &amp;#39;react&amp;#39;;
function Example() {  // Declare a new state variable, which we&amp;#39;ll call &amp;quot;count&amp;quot;  const [count, setCount] = useState(0);
  return (<div><p>You clicked {count} times</p><button onclick="{()"> setCount(count + 1)}&gt;        Click me</button></div>
  );}

				

useEffect():

React has a built-in hook called the use effect. Hooks are used in functional components.

If using class components in that no have to build the use effect. Use effects only work for the Functional component

Three phases are supported in useEffect():

  • componentDidMount

  • componentDidUpdate

  • componentWillUnmount


useEffect(()=&gt;{
console.log(&amp;lsquo;render&amp;rsquo;);
return()=&gt;console.log(&amp;lsquo;unmounting&amp;rsquo;);
})

				

Here, you have to just pass some value in an empty array which is defined in a syntax that runs on the mount and on unmount time. It does not get any load time or refresh page time.


useEffect(()=&gt;{
console.log(&amp;lsquo;render&amp;rsquo;);
return()=&gt;console.log(&amp;lsquo;unmounting&amp;rsquo;);
})

				

useContext()

The current context value is considered by the value prop of the first above the calling component in the above tree.

The useContext( ) method accepts a context within a functional component and works with a . Provider and. Consumer component in one call.


Const value=useContext(MyContext);

const themes = {
    light: {
      foreground: &amp;quot;#000000&amp;quot;,
      background: &amp;quot;#eeeeee&amp;quot;
    },
    dark: {
      foreground: &amp;quot;#ffffff&amp;quot;,
      background: &amp;quot;#222222&amp;quot;
    }};
  const ThemeContext = React.createContext(themes.light);
  function App() {
    return (
      <themecontext.provider value="{themes.dark}">      <toolbar />    </themecontext.provider>
    );}
  function Toolbar(props) {
    return (
<div>      <themedbutton /></div>
    );}
  function ThemedButton() {  const theme = useContext(ThemeContext);  return (<button background:="" style="{{" theme.background="">      I am styled by theme context!</button>  );}
  

				

Conclusion

React component patterns concept is all about the features and functionalities used in React platform. In this blog, we have gone through various kinds of libraries used in React.

A comprehensive guide on advanced React Component Patterns Table of Content 1. What are React Patterns? 2. Component patterns in react 2.1 Higher-Order Component 2.2 Conditioal Rendering 2.3 Create the Provider 3. Conclusion What are React Patterns? React Patterns means how react handle the flow of code, which type of criteria it followed and how to manage whole things, it’s all about its workflow life cycle. Component patterns in react Higher-Order Component Once you create one component and that code will be used in your entire project more than one time that time you take the component as HO, C first you create a component in your project you can use multiple times in your project, that is a benefit you do not have to write a code more and more time its increase the higher performance of React its also increase the readability of React. Example: import React from &#39;react&#39;;// Take in a component as argument WrappedComponentconst higherOrderComponent = (WrappedComponent) => {// And return another component class HOC extends React.Component { render() { return ; } } return HOC;}; Passing props: React is unidirectional it decreases the complexity of code it makes it easier for developers. Data are passed from parent component to child components and the entire process of the props will be immutable it's just getting the direction from parent to a child not change the props value. Reused Component: react is component-based, in react you can read any component in the other component its also increase the readability of React. Spread and Rest operators : The spread operator allows you to get elements out of an array (=> split the array into a list of its elements) or get the data out of an object. Spread: used to split up array element or object properties: Rest: used to merge a list of function arguments into an Array Destructuring: Array Destructing: easily extract array elements and store them in a variable. [a,b] = [ &lsquo;add&rsquo; , &rsquo;sub&rsquo;] Console.log (a ); // Print &ldquo;add&rdquo; Console.log (b ); //print &ldquo;sub&rdquo; Object Destructing:easily extract object element and strore them in variable. {name} = { name: &rsquo;max&rsquo; , age:29 } Console.log(name); //print max Console.log(age); //print undefined Read More: A Complete Guide On React Fundamentals: Props And State   Conditioal Rendering If-Else Condition operator : if(a>b) { console.log(a); } else { console.log(b); } Ternary operator : render() { return ( {this.state.showWarning ? &#39;Hide&#39; : &#39;Show&#39;} ); } Array and list: function NumberList(props) { const numbers = props.numbers; const listItems = numbers.map((number) =>{number} ); return ({listItems} ); } const numbers = [1, 34, 3, 4, 52]; ReactDOM.render( , document.getElementById(&#39;root&#39;) ); Keys: is a uniquely identify the rows which data is deleted updated that time it's useful for apply unique id. const numbers = [1, 34, 3, 4, 52]; const listItems = numbers.map((number) => {number} ); [contextAPI] Create the Provider First, we have to create a provider which is defined in syntax and pass the value in the value tag after creating the provider you have to create a consumer and initialize and create the consumer creation. Which define all syntax in the below code and consider the one example you getting more easily thorough this code Create the consumer < MyContext.Consumer> {value => / create context value/} Initializing Content: export const ThemeContext = React.createContext({ theme: themes.dark, toggleTheme: () => {},}); Consumer Creation: function Layout() { return ( );} // A component may consume multiple contextsfunction Content() { return ( {theme => ( {user => ( )} )} );} Looking to Hire React Developers ? Your Search ends here. See here   Layout component: Layout Component work like that As its name states - it defines the layout of the application. It simply accepts children as props and renders them to the DOM together or without other child components. import React from &#39;react&#39;; const Layout =({children}) =>{ return( <> {children} </> )} export default Layout; Hooks Component: Hooks and their advanced features are established in ES6. Using the hooks component, we can set the state in the function component. We can even use componentDidMount and componentUnmount with hooks components to pass the context. UseState: It is a Hook (function) that allows you to have state variables in functional components. Example: import React, { useState } from &#39;react&#39;; function Example() { // Declare a new state variable, which we&#39;ll call &quot;count&quot; const [count, setCount] = useState(0); return (You clicked {count} times setCount(count + 1)}> Click me );} useEffect(): React has a built-in hook called the use effect. Hooks are used in functional components. If using class components in that no have to build the use effect. Use effects only work for the Functional component Three phases are supported in useEffect(): componentDidMount componentDidUpdate componentWillUnmount useEffect(()=>{ console.log(&lsquo;render&rsquo;); return()=>console.log(&lsquo;unmounting&rsquo;); }) Here, you have to just pass some value in an empty array which is defined in a syntax that runs on the mount and on unmount time. It does not get any load time or refresh page time. useEffect(()=>{ console.log(&lsquo;render&rsquo;); return()=>console.log(&lsquo;unmounting&rsquo;); }) useContext() The current context value is considered by the value prop of the first above the calling component in the above tree. The useContext( ) method accepts a context within a functional component and works with a . Provider and. Consumer component in one call. Const value=useContext(MyContext); const themes = { light: { foreground: &quot;#000000&quot;, background: &quot;#eeeeee&quot; }, dark: { foreground: &quot;#ffffff&quot;, background: &quot;#222222&quot; }}; const ThemeContext = React.createContext(themes.light); function App() { return ( );} function Toolbar(props) { return ( );} function ThemedButton() { const theme = useContext(ThemeContext); return ( I am styled by theme context! );} Conclusion React component patterns concept is all about the features and functionalities used in React platform. In this blog, we have gone through various kinds of libraries used in React.

Author Bio

User Image

Author Name : Rajal Parmar

Rajal Parmar is a dexterous React enthusiast. She is passionate about mobile app development and believes in constant learning and development strategies. She avidly shares her insights over various platforms.

Categories

Ensure your sustainable growth with our team

Talk to our experts
Sustainable
Sustainable
 

Blog Our insights

A complete guide on eCommerce conversion rate optimization
A complete guide on eCommerce conversion rate optimization

Table of Content 1. Define your goals 2. Know your target audience 3. Simplified UI/UX design, simple navigation, and high resolution images 4. Design a dedicated landing...

Read More
A comprehensive guide on the Construction management software
A comprehensive guide on the Construction management software

Table of Content 1. Mobile compatibility and inventory management 2. Accurately forecast job costs and monitor them 3. STACK 4. On-premises software is better suited...

Read More
Java And Environment Variables: A Brief Overview
Java And Environment Variables: A Brief Overview

Java is one of many programming languages that have shown much promise in the coding world. With that said, there are many components to consider, when working with Java, including...

Read More