React.js (also referred to as ReactJS or React) is a popular JavaScript library for creating wonderful user interfaces.
One of the notable features of React is that it relies on a component-focused approach for building interactive UIs.
Maxim-Filimonov, who has more than ten years of experience in the software development industry and presently teaches people his skills, says that “adhering to the React API best practices when creating components will assist you to write high-quality and clean React code.”
Click here to watch and learn from one of his projects on How to Build Cross-platform Mobile App in React Native.
Here are three React tips and best practices you need to take your development skills a notch higher.
-
Avoid creating new components unnecessarily
Here is an example of a React component:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 |
export default class Liveedu extends PureComponent { static propTypes = { userIsLearning: PropTypes.bool, user: PropTypes.shape({ _id: PropTypes.string, }).isNeeded, } static defaultProps = { userIsLearning: false, } render() { const { userIsLearning, user } = this.props; if (!userIsLearning) return <Learning />; return ( <div> <div className="two-col"> <section> <LearnOnline userId={user.id} /> <Watching projects userId={user._id} /> </section> <aside> <UserDetails user={user} /> <WatchProjects user={user} /> </aside> </div> <div className="one-col"> {isInfo('student', user={user._id} && <LearnersInfo userId={user._id} /> } </div> </div> ) } } |
As you can see from the above code, we have a single component called Liveedu. We’ve included other components like LearnOnline and WatchProjects inside this huge component.
Since we are taking all the data from the same location (user), we could have just declared the components separately.
However, to achieve conciseness, we opted to include the smaller components inside one component.
Whereas there are no black and white rules concerning how to create a new component for your React code, the following guidelines are worthwhile:
- If you are going to reuse your code, consider creating new components for each functionality.
- If you want each component to represent a specific functionality, then making new components can be a good idea.
- If your code is becoming unwieldy and cluttered, improve readability by creating new components.
-
Know when to use Component, Stateless Functional Component, and PureComponent
Another best practice when creating React code is to know when to use the various types of components.
Here is a code sample that shows how to create a Stateless Functional Component:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 |
const Liveedu = () => ( <WatchProjects> <H1>Programming Projects</H1> <div className="learn_online"> <Link className="liveedu_project_image" to="/"> <img alt="experts building projects" src="liveedu.jpg"> </Link> <div className="Project Learning Platform"> <h2 className="create">Programming Projects</h2> <li>JavaScript</li> <li>PHP</li> <li>Angular</li> </div> </div> </WatchProjects> ); |
This type of component will assist you to write clean and uncluttered React code.
You can use them to make components that are not relying on any type of refs, state, or other lifecycle methods.
Therefore, you’ll not be concerned about state manipulation or lifecycle methods, which will not force you to install libraries for performing tests.
Just like the name suggests, this component is without any state; it’s just a function.
Therefore, it assists you to define a component just like a constant function that returns the required data.
In other words, it is a function that is used to return JSX.
In the above first code sample, you might have realized that we declared Liveedu as PureComponent instead of using the traditional Component.
PureComponent is often used to prevent React from re-rendering unnecessarily. Whenever a component receives a new prop, it will automatically be re-rendered.
This will take place even when a component has received a new prop without any changes.
For example, if a prop is referencing a string or Boolean value, and changes take place, a PureComponent can detect that.
On the other hand, whenever a property inside an object experiences any changes, a PureComponent cannot initiate React re-rendering.
Therefore, you can use PureComponent in place of Component to ensure re-rendering takes place only when necessary.
-
Use spread attributes sparingly
The … (three dots) spread operator is useful for achieving brevity in your React code.
Here is a code sample that selects specific props that a component consumes and uses the spread operator to pass the entire props object.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 |
const Liveedu = props => { const { kind, ...other } = props; const className = kind === "primary" ? "PrimaryButton" : "SecondaryButton"; return <button className={className} {...other} />; }; const App = () => { return ( <div> <Button kind="primary" onClick={() => console.log("clicked to start learning")}> Watch Experts Create Practical Projects </Button> </div> ); }; |
In the above code, the kind prop is consumed without any issues. Furthermore, it is not passed to the <button> element in the Document Object Model (DOM).
Also, the other props are passed using the …other object, which adds some flexibility to this component. In fact, it passes an onClick and children props, as shown on the code.
Whereas using spread attributes in your components can be beneficial, it increases the chances of passing needless props to components that do not care about their existence.
Furthermore, this syntax can make you pass unwarranted HTML attributes to the DOM.
Therefore, using them sparingly is better.
Wrapping up
React components are the cornerstone to creating powerful and intuitive user interfaces.
The above-mentioned best practices will give you the confidence you need to take React.js by its horns and escalate your front-end development skills to the next level.
What other React.js best practices do you know?
Please share your comments below.