Serving Industries Worldwide

Innovative Ways - Satisfied Clientele

A comprehensive guide on advanced React Component Patterns


Listening is fun too.

Straighten your back and cherish with coffee - PLAY !

 
 

A_Comprehensive_Guide_on_Advanced_React_Component_Patterns

Table of Content

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] = [ ‘add’ , ’sub’]
Console.log (a ); 
// Print “add”
Console.log (b );
//print  “sub”
Object Destructing:easily extract object element and strore them in variable.
{name}  =  {  name: ’max’ , age:29 }
Console.log(name);
//print  max
Console.log(age);
//print  undefined 



Conditioal Rendering

If-Else Condition operator :

if(a>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 ? 'Hide' : 'Show'}
        </button>
      </div>
    );
  }
Array and list:

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

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) =>
  <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={/* some value */}></MyContext.Provider>

Create the consumer

 < MyContext.Consumer>
  {value => / create context value/}</MyContext.Consumer>
Initializing Content:

export const ThemeContext = React.createContext({  theme: themes.dark,  toggleTheme: () => {},});
Consumer Creation:

function Layout() {
    return (
      <div>      <Sidebar />      <Content />    </div>
    );}
  // A component may consume multiple contextsfunction Content() {
    return (    <ThemeContext.Consumer>    
    {theme => (        <UserContext.Consumer>       
     {user => (            <ProfilePage user={user} theme={theme} />        
    )}        </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 'react';
const Layout =({children}) =>{
    return(
        <>
        <div>
            <ToolBar/>
            <Sides/>
            <Backdrop/>
        </div>
        <main>{children}</main>
        </>
    )}
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 'react';
function Example() {  // Declare a new state variable, which we'll call "count"  const [count, setCount] = useState(0);
  return (
    <div>      <p>You clicked {count} times</p>      <button onClick={() => setCount(count + 1)}>        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():

  1. componentDidMount
  2. componentDidUpdate
  3. componentWillUnmount

useEffect(()=>{
console.log(‘render’);
return()=>console.log(‘unmounting’);
})

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(‘render’);
		return()=>console.log(‘unmounting’);
	},[])
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: "#000000",
      background: "#eeeeee"
    },
    dark: {
      foreground: "#ffffff",
      background: "#222222"
    }};
  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 style={{ background: theme.background, color: theme.foreground }}>      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

A_Comprehensive_Guide_on_Advanced_React_Component_Patterns

Table of Content

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] = [ ‘add’ , ’sub’]
Console.log (a ); 
// Print “add”
Console.log (b );
//print  “sub”
Object Destructing:easily extract object element and strore them in variable.
{name}  =  {  name: ’max’ , age:29 }
Console.log(name);
//print  max
Console.log(age);
//print  undefined 



Conditioal Rendering

If-Else Condition operator :

if(a>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 ? 'Hide' : 'Show'}
        </button>
      </div>
    );
  }
Array and list:

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

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) =>
  <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={/* some value */}></MyContext.Provider>

Create the consumer

 < MyContext.Consumer>
  {value => / create context value/}</MyContext.Consumer>
Initializing Content:

export const ThemeContext = React.createContext({  theme: themes.dark,  toggleTheme: () => {},});
Consumer Creation:

function Layout() {
    return (
      <div>      <Sidebar />      <Content />    </div>
    );}
  // A component may consume multiple contextsfunction Content() {
    return (    <ThemeContext.Consumer>    
    {theme => (        <UserContext.Consumer>       
     {user => (            <ProfilePage user={user} theme={theme} />        
    )}        </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 'react';
const Layout =({children}) =>{
    return(
        <>
        <div>
            <ToolBar/>
            <Sides/>
            <Backdrop/>
        </div>
        <main>{children}</main>
        </>
    )}
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 'react';
function Example() {  // Declare a new state variable, which we'll call "count"  const [count, setCount] = useState(0);
  return (
    <div>      <p>You clicked {count} times</p>      <button onClick={() => setCount(count + 1)}>        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():

  1. componentDidMount
  2. componentDidUpdate
  3. componentWillUnmount

useEffect(()=>{
console.log(‘render’);
return()=>console.log(‘unmounting’);
})

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(‘render’);
		return()=>console.log(‘unmounting’);
	},[])
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: "#000000",
      background: "#eeeeee"
    },
    dark: {
      foreground: "#ffffff",
      background: "#222222"
    }};
  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 style={{ background: theme.background, color: theme.foreground }}>      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.

Author Bio

Author

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.