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

Final thoughts on reusability

Final Thoughts on Reusability

In this tutorial, we summarize the journey into mastering reusable components in React by focusing on two key features: default props and prop type validation. These tools are essential for creating robust and developer-friendly components. Along the way, we’ll also discuss how these practices have evolved and introduce alternative approaches available in 2024.


What Are Default Props?

Default props in React provide fallback values for a component's props in case no value is explicitly provided. This ensures your component has predictable behavior, even when data is missing.

Example:
class TextFooter extends React.Component {
  static get defaultProps() {
    return {
      title: "You forgot the title",
      content: "Default content here",
    };
  }

  render() {
    const { title, content } = this.props;
    return (
      <div>
        <h3>{title}</h3>
        <p>{content}</p>
      </div>
    );
  }
}

If you fail to pass title or content, the component will automatically use the default values.


What Are Prop Types?

Prop types validate the props passed to a component during development, ensuring they are of the correct type or structure. This feedback is invaluable, especially in collaborative projects.

Example:
import PropTypes from 'prop-types';

class TextFooter extends React.Component {
  static get propTypes() {
    return {
      title: PropTypes.string.isRequired,
      content: PropTypes.node.isRequired,
    };
  }

  render() {
    const { title, content } = this.props;
    return (
      <div>
        <h3>{title}</h3>
        <p>{content}</p>
      </div>
    );
  }
}

If a required prop is missing or of an incorrect type, React will log a descriptive error in the console during development.


Enforcing Specific Conditions

There are scenarios where you want to ensure specific conditions are met, such as a component having only one child. React’s PropTypes.element.isRequired can enforce such constraints.

Example:
class SingleChildComponent extends React.Component {
  static get propTypes() {
    return {
      children: PropTypes.element.isRequired,
    };
  }

  render() {
    return <div>{this.props.children}</div>;
  }
}

If the component receives more than one child, React will throw an error during development.


Reusability in Modern React (2024)

The concepts of default props and prop validation remain foundational, but modern React introduces additional features and tools that further simplify reusability:

1. TypeScript for Prop Validation

While PropTypes is excellent for runtime validation, many developers now prefer TypeScript for compile-time prop validation. It allows more robust type-checking and eliminates the need for PropTypes entirely.

Example with TypeScript:
type TextFooterProps = {
  title: string;
  content: React.ReactNode;
};

const TextFooter: React.FC<TextFooterProps> = ({ title, content }) => (
  <div>
    <h3>{title}</h3>
    <p>{content}</p>
  </div>
);

TypeScript ensures type safety during development and can catch errors before running the application.


2. Using Context for Default Values

For shared defaults across multiple components, React Context is a powerful tool. Instead of setting defaults at the component level, you can define them globally and avoid repetition.

Example:
const DefaultValuesContext = React.createContext({
  title: "Default Title",
  content: "Default Content",
});

const TextFooter = () => {
  const { title, content } = React.useContext(DefaultValuesContext);
  return (
    <div>
      <h3>{title}</h3>
      <p>{content}</p>
    </div>
  );
};

Why Focus on Reusability?

Reusable components save time, improve consistency, and reduce maintenance effort. By combining traditional practices like PropTypes and default props with modern techniques like TypeScript and Context, you create flexible and scalable components.

Key Takeaways:

  1. Use default props to define fallback values for missing props.
  2. Validate prop types using PropTypes or TypeScript for better reliability.
  3. Leverage Context for managing shared defaults across your application.
  4. Continuously refactor components to keep them modular and reusable.

In the next section, we’ll step beyond individual components and learn how to bundle them into a complete single-page application. Stay tuned as we bring it all together!

Video Transcript

00:01Reusability has many phases,
00:03but for the last lecture in this section, I wanted
00:06to spend a little bit more time overall big picture
00:09reusability as we explore default values.
00:12And also how do we confirm
00:13that a component only has one child that can happen,
00:16that you need a situation like that.
00:20So let's jump right into it.
00:24Alright, we're nearing the end of this section
00:26and I wanted to wrap things up with just a few more things
00:29that will help make your components more
00:32reusable and more shareable.
00:34Now, one of those stuff, two things that we're gonna cover
00:36and I want to talk, it's really about giving error messages
00:39and giving feedback to developers
00:42and users as they need them.
00:43So in this case, I'm gonna go back into the text
00:45footer to showcase this.
00:47And what I wanna do is I want to create a new static getter.
00:50And this getter is gonna be called default props.
00:54Default props.
00:56Now the default props getter in our case,
00:59in our ees six class example here is gonna return an object
01:03that mimics the objects that you want
01:05to have default values in them in this case.
01:08And if you did not set a title, I wanna say that Ben,
01:12you forgot, uh, you forgot the title for example.
01:16But really in reality, you would might wanna put,
01:19uh, how about Ben?
01:20You forgot a title. And for our content, I'm gonna put here,
01:23Ben, you still rock?
01:25Yay. Thanks for the compliment.
01:27This is the, I used to long ago, uh, put it into my text,
01:32curse words and stuff like that.
01:33That is a big mistake.
01:35Instead of that put always positive things
01:37'cause then you're looking at it all day.
01:38And especially if your code ever would reach the out
01:42of the world, you don't want curse words inside there.
01:44So instead of that compliment yourself,
01:47that is a nice uplifting message in the end of this lecture.
01:50Now that we have these default values,
01:52they're not really gonna do much
01:53because we have content already inside.
01:56But if I go to one of our items, if I find the text footer
02:00and for example, someone didn't send the data in right,
02:03then those defaults will be applied
02:05automatically or vice versa.
02:07If the model itself has any issues, for example,
02:11in our client, let's say our model comes back,
02:13but it comes back without the content, it's content free.
02:16It just has a title for some reason, even in that situation,
02:20it will use those defaults, which is really, really useful.
02:24So creating these default scenarios could really help
02:27elevate your component in situations
02:29where content doesn't come through.
02:31Could happen in this case.
02:32'cause we're working all with content that's pretty big.
02:34Maybe it won't happen. But in a real world scenario,
02:37there might be a server error,
02:38there might be, I don't know what.
02:40And in that case it's a really great idea
02:42to have default values
02:43and that's exactly how you create and react.
02:46But creating the default props at, um, getter
02:50and sending through it an object
02:52that will mimic the different items that you want
02:54to put their default values.
02:55Now last thing that I want to talk about
02:57before we wrap things up are still
02:58Inside of the prop types.
03:00And I just wanted to say
03:01that you could also define in the prop types your children.
03:05So you could do only the children and or all the children.
03:07In this case, we don't have a chil children at all.
03:10But let's say we wanted to define children
03:12and we want the, the this item to only work.
03:15If the property types, um, is an element,
03:19not only is the denel,
03:20but this should be about lowercase by the way.
03:23Um, we want to say that it is required.
03:26And in this case, what's gonna actually happen,
03:28we're gonna get an error message telling me, Hey,
03:30by the way, your text footer is not complete
03:32because you don't have children.
03:34You must have one child.
03:36And if we go ahead and render it again, you'll see
03:38that Now we're gonna get errors, we got disconnected.
03:41How weird. Let's refresh. Ooh, our server dropped.
03:46That is so crazy. Cool. Okay, so let's check what happened.
03:52Yeah, there we go. We crashed for some reason, a trap.
03:55How interesting. Okay, that could happen.
03:58So we started up our server again
04:00and let's see if it's working.
04:03And now that it's working, working yet those error message
04:05that is gonna tell us, by the way, you should,
04:08should have children here, but you didn't put children
04:10in your text footer.
04:11So that's really powerful stuff.
04:13In this case, we really, in this case,
04:15we really don't need it.
04:16But that is another way
04:18to make your components more visible.
04:20So if you need to have a child
04:21and only one child, make sure that you put that in
04:24and you configure it to make sure
04:25that whoever's running your code will get a very valid error
04:28message that tells 'em exactly what's missing in their code.
04:32'cause in reality we could have said, Hey,
04:34the content shouldn't be, uh, listed out this way,
04:37but instead of that, we wanna put the content wrapped down
04:39and send a child just like we've done
04:41in previous videos before.
04:42So that's it. That is really all the important things you
04:44need to know about to create reusable components.
04:48So you, in the next section, our last section,
04:51which is gonna be really, really wicked,
04:54where we connect all the dots together
04:56to create our full project.
04:59In this lecture we really echoed the importance
05:02of validation and saw a few different cool features such
05:05as default values
05:07that really make our components stand up
05:09in their reusability.
05:11In the next section, we're gonna walk away from just about
05:14reusability into bundling everything together
05:17to create a single page application.
05:20Okay?

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!