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>;
Leveraging React's defaultProps component property
const Greeting = (props) => <h1>{props.message}</h1>;
Greeting.defaultProps = {
message: 'No message prop provided!'
}
Using Object Destructuring Assignment
const Greeting = ({ message = 'No message prop provided!' }) =>
<h1>{message}</h1>;
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!' }) => (
<h1>{message}</h1>
)
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);
Have any more tips? I'd love to know more!
Top comments (0)