Some tips & tricks that will help you control ReactJS more easily (Part 3)

Tram Ho

Use Error Boundaries

Javascript errors in part of UI should not affect the whole application. To solve this problem for React users, React 16 introduces a new concept called “Error Boundary” Error Boundaries are React components wrapped around to catch errors of child components.

When any error occurs at <Home /> component, it is re- <ErrorBound/> by <ErrorBound/> component. So instead of rendering a blank page and throwing an UnCatch error, then <ErrorBound/> will catch an error, report an error at the console and render a replacement component.

<ErrorBound/> component:

The function getDerivedStateFromError () updates the state when there is an error, to trigger re-render an element | component replacement.

The componentDidCatch () method to catch the error and log it to the console to trace bugs from the error stack.

React & Typescript

Typescript is a hot topic and one of the top choices developers have to explore in the near future. With new versions of create-react-app (CRA), it came with support for Typescript. We only need to append the typescript flag when creating a new project vs CRA:

Some benefits of integrating Typescript with react include: Latest Javascript features built-in, readability and validation to minimize errors during development, …

Here is a simple example of using Typescript in a component component:

or with an interface:

If you want to try something new in 2020, let’s shake hands vs Typescript to try it out.

Jest + Enzyme for Testing

Testing your applications is something every developer should do and it is a must in many projects. Jest + Enzyme are 2 libraries that are widely used to write unit tests for React.

Jest comes with create-react-app. It provides a snapshot testing to compare if there is any change in the current component compared to its previous state. If they do not match, the result will be fail.

Enzyme is a utility used in Javascript testing for React. It was developed by Airbnb and is an ideal partner for Jest.

With these libraries, we can perform neat tests like:

to test the basic rendering behavior of a component. But we can do much more, for example testing for props:

Very helpful, right? And there are many things you can do with them, such as mocking API mode or testing lifecycle methods …

Epilogue

Above is an article on some tips that can help you in getting acquainted and using ReactJS. Hope you will have the passion to transform it into passion vs ReactJS

refer:

Share the news now

Source : Viblo