DEV Community

Ezell Frazier
Ezell Frazier

Posted on


Low Cost Value-Adds for Any React Project

Landed a new role? New to a React project? Just want to see if there's anything new here?

Here are a few ways to hit the ground running with minimal cost to existing codebases. Free of any package installations.

Default Props

It is not uncommon to discover legacy or current React codebases with components containing no default values for the props it consumes. Which implies the value undefined is part of expected behavior, which is risky business.

// What should we see if the message prop isn't provided?
const Greeting = (props) => <h1>{props.message}</h1>;
Enter fullscreen mode Exit fullscreen mode

Leveraging React's defaultProps component property

const Greeting = (props) => <h1>{props.message}</h1>;

Greeting.defaultProps = {
  message: 'No message prop provided!'
Enter fullscreen mode Exit fullscreen mode

Using Object Destructuring Assignment

const Greeting = ({ message = 'No message prop provided!' }) => 
Enter fullscreen mode Exit fullscreen mode

Adding TypeScript Types via JSDoc

It's safe to assume numerous React developers are using Visual Studio Code as their text editor. Why not enhance the development experience by leveraging VSCode's Intellisense?

Adding types via React Prop Types or TypeScript may face some resistance, but it doesn't mean we can't use types with comments.

 * @description defaults to "No message prop provided!"
 * @param {{ message: string }} { message }
 * @returns {JSX.Element} Greeting component
const Greeting = ({ message = 'No message prop provided!' }) => (
Enter fullscreen mode Exit fullscreen mode

Learn more Here

Explanatory Comments

I admit, this is a piece of advice for myself as much as it is for anyone else. Also, this is a general good habit for any project.

Ideally, we want to write comments explaining why we're adding a component or a highly re-used module.

If we can't explain it in a line, try to include a reference to the ticket.

Received a hard-to-understand piece of code from the internet? Include a link to where it was found.

Your teammates and future-self will greatly appreciate this.

// Wanted a concise way to compose the props for a hairy view
// See ticket #4207 for details
export const pipe = (input, ...fns) =>
  fns.reduce((output, fn) => fn(output), input);
Enter fullscreen mode Exit fullscreen mode

Have any more tips? I'd love to know more!

Top comments (0)

An Animated Guide to Node.js Event Loop

Node.js doesn’t stop from running other operations because of Libuv, a C++ library responsible for the event loop and asynchronously handling tasks such as network requests, DNS resolution, file system operations, data encryption, etc.

What happens under the hood when Node.js works on tasks such as database queries? We will explore it by following this piece of code step by step.