02Geek HTML5 and JavaScript, TypeScript, React, Flash, ActionScript online School
Previous VideoNext Video

Creating Reusable Utilities for React Components

In modern React development, reusability is king. As applications grow, the need for shared, modular logic becomes essential. In this tutorial, we’ll explore how to create reusable utilities for your React components. By the end, you’ll be equipped to handle shared non-visual logic efficiently, making your code cleaner, more maintainable, and ready for future expansion.


Why Reusable Utilities?

React’s component-based architecture thrives on reusability. However, while we often think about reusing visuals, non-visual logic is equally important. Utilities allow developers to extract common functions and make them accessible to multiple components without redundancy. This is especially critical for maintaining clean separation of concerns and ensuring components remain lightweight and focused.


Step-by-Step Guide

  1. Identify Shared Logic
    Begin by identifying logic that is used across multiple components. In our case, the classify method, initially built into the Button component, is a perfect candidate. This function dynamically adds or modifies CSS class names, making it useful beyond just buttons.

  2. Create a Utility File
    Create a dedicated file, such as utils.js, within your project. This file will house reusable functions like classify. Keep it organized and focused on non-visual logic to ensure clarity.

    // utils.js
    export function classify(key, value) {
        if (value.startsWith('-')) {
            value = `${key}${value}`;
        }
        return value
            .split(' -')
            .join(` ${key}-`);
    }
    
  3. Export Functions for Reuse
    By using named exports, you can bundle multiple utilities within the same file. This avoids locking functions into a single default export, making them easier to manage and scale.

    export { classify };
    
  4. Import and Use Utilities
    Within your components, import utilities selectively using ES6’s deconstructing import syntax. This reduces bloat and ensures only necessary logic is included.

    import { classify } from './utils';
    
    const className = classify('btn', '-primary');
    

Best Practices for Utility Creation

  • Scope Appropriately: Keep utility functions narrowly focused. Avoid overloading them with responsibilities to maintain clarity.
  • Avoid Inheritance: Rely on composition rather than extending React's base classes for shared logic. Utilities should function independently.
  • Organize by Purpose: Group utilities logically (e.g., by framework or feature) to make finding and managing them intuitive.

How This Fits into the Bigger Picture

This foundational step prepares us for creating dynamic, reusable components like the Jumbotron. By centralizing shared logic in utilities, we streamline component creation and maintenance, fostering a cleaner and more scalable codebase.

In the next lesson, we’ll dive into the visual aspect of the Jumbotron, leveraging this utility to ensure consistency and reusability across our application.

Video Transcript

00:00We already created our first component,
00:03really a full scale button component in our last section.
00:07This section is gonna be dedicated to another component,
00:09but a much more complex one, the jumbotron component.
00:13Through this section, you're architect gonna learn about how
00:15to make reusable logic and how to make reusable visuals
00:20and how to just make components better that are dynamic
00:25with children and properties.
00:27With that said, let's jump right into our first lecture.
00:30Our first lecture is about creating a utility
00:32for non-visual elements.
00:34And the real question is, where do you put non-visual logic
00:37that you need to reuse in more than one class?
00:40And that's exactly what we're gonna answer in this lecture.
00:44Alright. We created one component
00:47that is really gonna be incredibly useful when we're
00:50creating applications that are leveraging bootstrap.
00:54Now I wanna create another one,
00:55but this time around we're gonna be a lot faster.
00:58And the next one that I want to create,
00:59and let me just put everything in the window,
01:02is the jumbotron.
01:04Now, even before I start building our jumbotron,
01:06there is similarities between our jumbotron
01:09and our button for one, that name itself
01:12that we're placing or that key.
01:14And then after that, our continuation with that fluid part.
01:18So just like with when we have your without the uh button
01:22where we automatically refill it, we really want
01:24to do the same for our jumbotron as well.
01:27Lemme just word wrap here
01:29so we could see things a little bit more clearly.
01:31So let's go ahead and start planning that out to make
01:34that feasible possible.
01:36And an option. And really what we want to do is we want
01:39to extract out our classify method from the button
01:43and turn it into something that is a utility
01:45that is accessible beyond.
01:47Now, if you have any experience
01:49with object oriented programming previously, we don't want
01:54to use inheritance.
01:55If you don't know what inheritance is,
01:57then don't worry about it.
01:59But basically inheritance is this.
02:01In this case we have our button extending itself.
02:05It's extending its features from the React component itself.
02:09Now that's the only thing you really want to have
02:12that is built in inheritance, in React, all the rest,
02:16you really wanna build it in a way
02:17where you're just composing things
02:19and you want to use composition.
02:21In the case of our button,
02:23or in the case of the classify,
02:25we don't even need composition
02:27because this is really a utility function
02:29that is relevant really at any time
02:31that we need it to be relevant.
02:32It's non-visual, so to be able to use it,
02:35I'm just gonna go ahead and create here a new file
02:38and I'm gonna call it utils
02:39and it's living inside a bootstrap.
02:41So it's basically gonna be a utility package for Bootstrap.
02:45And what I'm gonna do is I'm gonna go ahead
02:47and grab out our method from our buttons of,
02:51let me find our button and I'm just gonna go ahead
02:53and chop it right out
02:55and place it inside of our utility, making sure that
02:58Because it's not a class, I'm gonna go ahead
03:01and type function because it is needed.
03:04Now, beyond that, I also want to export,
03:06but I don't wanna export it as the default as we've done
03:10so far because I'm probably gonna collect more methods
03:12that are gonna be utility methods
03:14that are gonna be used throughout Bootstrap.
03:17So I'm gonna go ahead
03:18and instead of setting it as a default,
03:20I won't place any default at all.
03:23And that's all I had to do to export multiple things.
03:25So I could have multiple exports
03:27and I don't need that default beyond
03:30that in my button itself.
03:32Whenever I want to fetch a specific item such as classify,
03:35I could literally, in my import statement,
03:38just import opening and closing a curly bracket
03:41and listing out with a comma all the items that I want
03:44to deconstruct or in this exportation.
03:48So in this case, I want to export classify,
03:51which currently is the only thing in there.
03:52So I'm deconstructing ca classify from the full
03:56utilities package.
03:58Now don't forget to put your dot,
04:00because this is not one of the built-in modules.
04:03It's actually sitting in the same folder.
04:05So I wanna make sure that I tell React to find it there
04:09or more accurately Tell JavaScript, tell E es six,
04:11tell Babel tell our com, our converter
04:15to know where to find the file.
04:16So lemme go ahead and save that.
04:17And if I go back into my application, hopefully even
04:21with this change, we should find out
04:23that nothing really changed
04:25unless something we've done here is wrong.
04:26So first of all, you could see this classifi is not a
04:29function, which is true enough
04:30because it's not a this anymore.
04:32So I have to go ahead here and undo the that this
04:35and save my file again.
04:37And if we go ahead and test it out,
04:39hopefully now everything is working just
04:41as is were is working.
04:43Previously in this lecture we learned about creating
04:47utilities as external modules for our React components
04:51so they could share that logic in the next lecture.
04:54We're gonna take a step back as we create our jumbotron
04:57before we actually solve the next problem, which will be
05:01visuals, reusable visuals.

Ready to Level Up Your Skills?

Join thousands of learners on 02GEEK and start your journey to becoming a coding expert today!

Enroll Now for Free!