We’ve teamed up with Open SourceCraft to bring you 6 Pro Tips from React Developers.
If you’re new to React, you could benefit from learning from the success—and failures—of React developers who’ve learned valuable lessons about the framework.
P.S. For a high-quality, in-depth introduction to React, you can’t go past Canadian full-stack developer Wes Bos. Try his course here, and use the code SITEPOINT to get 25% off and to help support SitePoint.
Tip 1: Use functional components
props as its argument and returns a React element.
Benefits of functional components:
- Less code
- Easier to understand
- The component is stateless, so you avoid accidentally storing state on a component you shouldn’t
- The component is simpler to test
- There’s no
- It’s easier to see where and when to extract smaller components
Tip 2: Keep your components small
Small components are easier to:
Extracting components will make your app more organized, more modular, and more structurally sound. Keep Tip 1 in mind and extract blocks of code into functional components whenever possible.
Tip 3: Understand how to handle
The first way to handle
this is to not handle it at all and use a functional component instead (see why that’s Tip No. 1?).
But if you are using an ES6 class, you’ll need to bind
this manually since React doesn’t autobind the functions inside that component.
There are several methods for doing so.
- Bind in render
- Use an arrow function in render
- Bind in constructor
- Use arrow function in class property
Check out the video to see these methods in practice.
Tip 4: Use a function in
setState, not an object
According to the React docs, React does not guarantee that state changes are applied immediately.
this.state right after calling
setState() is a potential pitfall because
this.state may not be what you think it is.
So instead of updating state with an object, update it with a function to avoid this potential pitfall.
Tip 5: Utilyze prop-types
prop-types is a library for typechecking props and can help prevent bugs by ensuring you are using the right datatypes for your props. This is an external package that you can install through npm or otherwise. Simply import the package, then add propTypes to your component and typeset accordingly. If you want the prop to be required, just add
Tip 6: Use React Developer tools
With React Developer Tools, available as a Google Chrome and Firefox extension, as well as a standalone app for other environments, you can quickly view your component hierarchy, inspect and edit a component’s props and state, and invoke methods on a component within the DevTools.