Higher-order components (HOCs) : to write reusable code

Higher-Order Components (HOCs): to Write Reusable Code

Photo by Irvan Smith on Unsplash

Higher-order components (HOCs) are functions that take a component and return a new component with enhanced functionality. HOCs can be used to write reusable code in React by encapsulating common functionality that can be reused across multiple components.

Let’s have a look at the various ways of writing HOCs.

Authentication HOC

An authentication HOC can be used to restrict access to certain components based on a user’s authentication status. The HOC can take a component as an argument, check the user’s authentication status, and conditionally render the component based on whether the user is authenticated or not. Here’s an example:

function withAuth(WrappedComponent) {
return function(props) {
const isAuthenticated = checkAuthStatus(); // Check user's authentication status
if (isAuthenticated) {
return <WrappedComponent {...props} />;
} else {
return <div>You need to be authenticated to access this component.</div>;
}
}
}

// Usage:
const AuthenticatedComponent = withAuth(MyComponent);

Logging HOC

A logging HOC can be used to log data or events that occur within a component. The HOC can take a component as an argument, log data or events at certain points in the component’s lifecycle, and render the component as usual.

function withLogging(WrappedComponent) {
return function(props) {
console.log('Component rendered:', WrappedComponent.name); // Log when the component is rendered
return <WrappedComponent {...props} />;
}
}

// Usage:
const LoggedComponent = withLogging(MyComponent);

Style HOC

A style HOC can be used to apply styles or CSS classes to a component based on certain conditions. The HOC can take a component as an argument, conditionally apply styles or CSS classes to the component, and render the component as usual. Here’s an example:

function withStyle(WrappedComponent) {
return function(props) {
const { color } = props;
const style = {
color: color || 'black',
fontWeight: 'bold'
};
return <div style={style}><WrappedComponent {...props} /></div>;
}
}

// Usage:
const StyledComponent = withStyle(MyComponent);

Data fetching HOC

A data-fetching HOC can be used to fetch data from an API and pass it as props to a component. The HOC can take a component as an argument, fetch data from an API, and render the component with the fetched data. Here’s an example:

function withData(WrappedComponent) {
return function WithDataComponent(props) {
const [data, setData] = useState([]);

useEffect(() => {
async function fetchData() {
const response = await fetch('https://api.example.com/data');
const data = await response.json();
setData(data);
}
fetchData();
}, []);

return <WrappedComponent data={data} {...props} />;
}
}

// Usage:
const DataComponent = withData(MyComponent);

Error handling HOC

An error-handling HOC can be used to catch and handle errors that occur within a component. The HOC can take a component as an argument, wrap it in a try-catch block, and conditionally render an error message if an error occurs. Here’s an example

function withErrorHandling(WrappedComponent) {
return function WithErrorHandlingComponent(props) {
const [error, setError] = useState(null);

function handleError(error, info) {
setError(error);
}

if (error) {
return <div>Something went wrong: {error.message}</div>;
} else {
return <WrappedComponent {...props} onError={handleError} />;
}
}
}

// Usage:
const ErrorComponent = withErrorHandling(MyComponent);

Role-based HOC

To check if the component is allowed for the mentioned role.

function withRoleAuthorization(WrappedComponent, allowedRoles) {
return function WithRoleAuthorizationComponent(props) {
const [userRole, setUserRole] = useState(null);

useEffect(() => {
const userRole = localStorage.getItem('userRole');
setUserRole(userRole);
}, []);

if (allowedRoles.includes(userRole)) {
return <WrappedComponent {...props} />;
} else {
return <div>Unauthorized Access</div>;
}
}
}

// Usage:
const AuthorizedComponent = withRoleAuthorization(MyComponent, ['admin', 'manager']);

Loader HOC

If your component needs a loader in case the component is calling an API and needs to show the loader until the API returns data.
This will help to avoid having a new state for the loader in all the components and importing a loader in every single component.

function withLoadingSpinner(WrappedComponent) {
return function WithLoadingSpinnerComponent(props) {
const [loading, setLoading] = useState(true);

useEffect(() => {
// add api calls here
const timeoutId = setTimeout(() => {
setLoading(false);
}, 2000);

return () => {
clearTimeout(timeoutId);
}
}, []);

if (loading) {
return <div>Loading...</div>;
} else {
return <WrappedComponent {...props} />;
}
}
}

// Usage:
const LoadingComponent = withLoadingSpinner(MyComponent);

In conclusion, Higher-Order Components (HOCs) are an extremely useful feature in React that allows you to write reusable code and abstract away common functionality from your components. By wrapping a component in a HOC, you can add functionality like data fetching, error handling, and authorization checks without cluttering up your component code with boilerplate code. We’ve discussed a number of different ways to write HOCs. With the help of HOCs, you can write more modular, reusable, and maintainable code in your React applications.

💡 Note: Using an open-source toolchain like Bit can also help with code reusability. Bit lets you easily share your code as reusable components across multiple projects, making it easier to maintain consistency and improve development efficiency. Find out more here.

Thank you for taking the time to read this post on writing reusable code in React! If you found this post useful, I would greatly appreciate it if you could follow and share the content. By doing so, you can help spread the knowledge and assist other developers in their journey to become more proficient in React. Additionally, if you have any further questions or topics you would like me to cover, feel free to let me know in the comments section. Thank you again for your support, and I look forward to continuing to provide you with valuable content in the future.

Build React Apps with reusable components, just like Lego

Bit’s open-source tool help 250,000+ devs to build apps with components.

Turn any UI, feature, or page into a reusable component — and share it across your applications. It’s easier to collaborate and build faster.

Learn more

Split apps into components to make app development easier, and enjoy the best experience for the workflows you want:

Micro-Frontends

Design System

Code-Sharing and reuse

Monorepo

Learn more:


Higher-order components (HOCs) : to write reusable code was originally published in Bits and Pieces on Medium, where people are continuing the conversation by highlighting and responding to this story.


This content originally appeared on Bits and Pieces - Medium and was authored by Kishor Patil

Higher-Order Components (HOCs): to Write Reusable Code

Photo by Irvan Smith on Unsplash

Higher-order components (HOCs) are functions that take a component and return a new component with enhanced functionality. HOCs can be used to write reusable code in React by encapsulating common functionality that can be reused across multiple components.

Let's have a look at the various ways of writing HOCs.

Authentication HOC

An authentication HOC can be used to restrict access to certain components based on a user’s authentication status. The HOC can take a component as an argument, check the user’s authentication status, and conditionally render the component based on whether the user is authenticated or not. Here’s an example:

function withAuth(WrappedComponent) {
return function(props) {
const isAuthenticated = checkAuthStatus(); // Check user's authentication status
if (isAuthenticated) {
return <WrappedComponent {...props} />;
} else {
return <div>You need to be authenticated to access this component.</div>;
}
}
}

// Usage:
const AuthenticatedComponent = withAuth(MyComponent);

Logging HOC

A logging HOC can be used to log data or events that occur within a component. The HOC can take a component as an argument, log data or events at certain points in the component’s lifecycle, and render the component as usual.

function withLogging(WrappedComponent) {
return function(props) {
console.log('Component rendered:', WrappedComponent.name); // Log when the component is rendered
return <WrappedComponent {...props} />;
}
}

// Usage:
const LoggedComponent = withLogging(MyComponent);

Style HOC

A style HOC can be used to apply styles or CSS classes to a component based on certain conditions. The HOC can take a component as an argument, conditionally apply styles or CSS classes to the component, and render the component as usual. Here's an example:

function withStyle(WrappedComponent) {
return function(props) {
const { color } = props;
const style = {
color: color || 'black',
fontWeight: 'bold'
};
return <div style={style}><WrappedComponent {...props} /></div>;
}
}

// Usage:
const StyledComponent = withStyle(MyComponent);

Data fetching HOC

A data-fetching HOC can be used to fetch data from an API and pass it as props to a component. The HOC can take a component as an argument, fetch data from an API, and render the component with the fetched data. Here’s an example:

function withData(WrappedComponent) {
return function WithDataComponent(props) {
const [data, setData] = useState([]);

useEffect(() => {
async function fetchData() {
const response = await fetch('https://api.example.com/data');
const data = await response.json();
setData(data);
}
fetchData();
}, []);

return <WrappedComponent data={data} {...props} />;
}
}

// Usage:
const DataComponent = withData(MyComponent);

Error handling HOC

An error-handling HOC can be used to catch and handle errors that occur within a component. The HOC can take a component as an argument, wrap it in a try-catch block, and conditionally render an error message if an error occurs. Here’s an example

function withErrorHandling(WrappedComponent) {
return function WithErrorHandlingComponent(props) {
const [error, setError] = useState(null);

function handleError(error, info) {
setError(error);
}

if (error) {
return <div>Something went wrong: {error.message}</div>;
} else {
return <WrappedComponent {...props} onError={handleError} />;
}
}
}

// Usage:
const ErrorComponent = withErrorHandling(MyComponent);

Role-based HOC

To check if the component is allowed for the mentioned role.

function withRoleAuthorization(WrappedComponent, allowedRoles) {
return function WithRoleAuthorizationComponent(props) {
const [userRole, setUserRole] = useState(null);

useEffect(() => {
const userRole = localStorage.getItem('userRole');
setUserRole(userRole);
}, []);

if (allowedRoles.includes(userRole)) {
return <WrappedComponent {...props} />;
} else {
return <div>Unauthorized Access</div>;
}
}
}

// Usage:
const AuthorizedComponent = withRoleAuthorization(MyComponent, ['admin', 'manager']);

Loader HOC

If your component needs a loader in case the component is calling an API and needs to show the loader until the API returns data.
This will help to avoid having a new state for the loader in all the components and importing a loader in every single component.

function withLoadingSpinner(WrappedComponent) {
return function WithLoadingSpinnerComponent(props) {
const [loading, setLoading] = useState(true);

useEffect(() => {
// add api calls here
const timeoutId = setTimeout(() => {
setLoading(false);
}, 2000);

return () => {
clearTimeout(timeoutId);
}
}, []);

if (loading) {
return <div>Loading...</div>;
} else {
return <WrappedComponent {...props} />;
}
}
}

// Usage:
const LoadingComponent = withLoadingSpinner(MyComponent);

In conclusion, Higher-Order Components (HOCs) are an extremely useful feature in React that allows you to write reusable code and abstract away common functionality from your components. By wrapping a component in a HOC, you can add functionality like data fetching, error handling, and authorization checks without cluttering up your component code with boilerplate code. We’ve discussed a number of different ways to write HOCs. With the help of HOCs, you can write more modular, reusable, and maintainable code in your React applications.

💡 Note: Using an open-source toolchain like Bit can also help with code reusability. Bit lets you easily share your code as reusable components across multiple projects, making it easier to maintain consistency and improve development efficiency. Find out more here.

Thank you for taking the time to read this post on writing reusable code in React! If you found this post useful, I would greatly appreciate it if you could follow and share the content. By doing so, you can help spread the knowledge and assist other developers in their journey to become more proficient in React. Additionally, if you have any further questions or topics you would like me to cover, feel free to let me know in the comments section. Thank you again for your support, and I look forward to continuing to provide you with valuable content in the future.

Build React Apps with reusable components, just like Lego

Bit’s open-source tool help 250,000+ devs to build apps with components.

Turn any UI, feature, or page into a reusable component — and share it across your applications. It’s easier to collaborate and build faster.

Learn more

Split apps into components to make app development easier, and enjoy the best experience for the workflows you want:

Micro-Frontends

Design System

Code-Sharing and reuse

Monorepo

Learn more:


Higher-order components (HOCs) : to write reusable code was originally published in Bits and Pieces on Medium, where people are continuing the conversation by highlighting and responding to this story.


This content originally appeared on Bits and Pieces - Medium and was authored by Kishor Patil


Print Share Comment Cite Upload Translate Updates
APA

Kishor Patil | Sciencx (2023-03-06T13:42:52+00:00) Higher-order components (HOCs) : to write reusable code. Retrieved from https://www.scien.cx/2023/03/06/higher-order-components-hocs-to-write-reusable-code/

MLA
" » Higher-order components (HOCs) : to write reusable code." Kishor Patil | Sciencx - Monday March 6, 2023, https://www.scien.cx/2023/03/06/higher-order-components-hocs-to-write-reusable-code/
HARVARD
Kishor Patil | Sciencx Monday March 6, 2023 » Higher-order components (HOCs) : to write reusable code., viewed ,<https://www.scien.cx/2023/03/06/higher-order-components-hocs-to-write-reusable-code/>
VANCOUVER
Kishor Patil | Sciencx - » Higher-order components (HOCs) : to write reusable code. [Internet]. [Accessed ]. Available from: https://www.scien.cx/2023/03/06/higher-order-components-hocs-to-write-reusable-code/
CHICAGO
" » Higher-order components (HOCs) : to write reusable code." Kishor Patil | Sciencx - Accessed . https://www.scien.cx/2023/03/06/higher-order-components-hocs-to-write-reusable-code/
IEEE
" » Higher-order components (HOCs) : to write reusable code." Kishor Patil | Sciencx [Online]. Available: https://www.scien.cx/2023/03/06/higher-order-components-hocs-to-write-reusable-code/. [Accessed: ]
rf:citation
» Higher-order components (HOCs) : to write reusable code | Kishor Patil | Sciencx | https://www.scien.cx/2023/03/06/higher-order-components-hocs-to-write-reusable-code/ |

Please log in to upload a file.




There are no updates yet.
Click the Upload button above to add an update.

You must be logged in to translate posts. Please log in or register.