7

Common React Hooks Mistakes You Should Avoid

 2 years ago
source link: https://blog.bitsrc.io/common-react-hooks-mistakes-every-developer-should-avoid-defd47d09d8c
Go to the source link to view the article. You can view the picture content, updated content and better typesetting reading experience. If the link is broken, please click the button below to view the snapshot at that time.

Common React Hooks Mistakes You Should Avoid

5 Common mistakes to avoid when using react hooks

React Hook feature was first introduced on React 16.8 update and became immensely popular among developers due to its capabilities. It allows you to hook into React state and lifecycle features. And, sometimes, it could be challenging when using it for advanced use cases.

In this article, I’ll discuss 5 common React Hooks mistakes every developer should avoid when building robust React applications.

1. Changing the Hooks Invocation Order

Hooks should not be called within loops, conditions, or nested functions since conditionally executed Hooks can cause unexpected bugs.

Avoiding such situations ensures that Hooks are called in the correct order each time the component renders. Also, it helps to keep the state of Hooks consistent across numerous useState and useEffect calls.

In the below example, I’ve created a basic React component to choose a person from the dropdown and displays the selected person’s data.

The SelectPerson component takes in the person’s id to be retrieved as a prop and keeps the personal data in the state variable person with the useEffect() Hook.

At a glance, everything looks fine, but you will get a console error since useState(), and useEffect() are not available in every render.

1*rYmxoFOTdm9MCir3jrMFhQ.png?q=20
common-react-hooks-mistakes-every-developer-should-avoid-defd47d09d8c
Screenshot by Author

To avoid this, you can simply move the return statement after the Hooks invocation.

So, always remember to use Hooks before any early returns at the top level of your React component.

2. Using useState when Re-Render is not Required

In functional components, you can use useState Hook for state handling. Although it is pretty straightforward, there can be unexpected issues if it is not used correctly.

For example, assume a component with two buttons. The first button will trigger a counter, and the second button will make a request based on the current counter state.

The above component will work fine. But, since we didn’t use state in the render phase, there will be unwanted re-renders each time the counter button clicks.

So, if you need to use a variable inside a component that preserves its state across renderings without triggering a re-render, useRef Hook would be a better option.

3. Handling Actions via useEffect

The useEffect Hook is one of the coolest methods for handling prop or state changes-related tasks. But, there can be situations where it makes things even more complex.

Suppose there is a component that takes a list of data and renders it to the DOM.

The first useEffect Hook handles the apiCall()on the initial render. If all the conditions are satisfied, the second useEffect will call the onSuccess() function.

However, there is no direct connection between the action and the invoked function. Therefore, we can’t guarantee that this scenario will only occur if the request is successful.

To handle such situations, we should move the onSucces() function inside the apiCall() function without using a separate Hook for that.

4. Using the Obsolete State

If you modify the useState multiple times in subsequent lines in your code, the results might surprise you.

In the above example, the Counter component increments the value of the state variable count. Since increaseCount() function calls the setCount() function 3 times, you might think that one button click will increase the count value by 3. But, it will only increment by 1 per button click.

The initial call to setCount(count + 1) increase the count appropriately, as count + 1 = 0 + 1 = 1. Similarly, the subsequent two calls of setCount(count + 1) too set the count to 1 since it uses an obsolete state of the count.

This happens because the value of the state will only be updated in the next render.

This obsolete state issue can be resolved by updating the state in a functional approach.

5. Missing useEffect Dependencies

useEffect Hook is one of the most used Hooks in React, and it always runs on each re-render by default. However, this behaviour of cleaning up or applying the effect after each render can cause performance issues.

We can avoid these unwanted renderings by passing a dependency array to useEffect Hook.

useEffect Hook accepts dependency array as the second parameter, and it makes sure that effect will only run if the elements in the array are changed between re-renders.

Let’s consider the following example. It seems a well-working solution at a glimpse.

But, there is an issue, and you can find the below warning in the DevTools console.

Screenshot by Author

Note: Although it asks you to remove or keep the dependency array, you should not remove it since it will be a hack to trick React about dependencies.

To fix this the correct way, you need to ensure the array contains all the dependency values within the component scope that might vary with time and are used by the effect.

Otherwise, your code will use values from prior renderings that are no longer valid.

Build with independent components, for speed and scale

Instead of building monolithic apps, build independent components first and compose them into features and applications. It makes development faster and helps teams build more consistent and scalable applications.

Bit offers a great developer experience for building independent components and composing applications. Many teams start by building their Design Systems or Micro Frontends, through independent components.
Give it a try →

An independently source-controlled and shared “card” component. On the right => its dependency graph, auto-generated by Bit.

Final Thoughts

React Hooks are reusable, clean, and simple functions that can be incorporated into your workflow. In addition, they offer us many options for a diverse range of uses, so we don’t have to build them from scratch.

But, developers tend to make some significant mistakes when using React Hooks with advanced and custom features. In this article, I discussed 5 such common mistakes developers should avoid when using React Hooks.

I hope you will use them in your next React project and if you have any suggestions, please share them in the comments section.

Thank you for Reading !!!


About Joyk


Aggregate valuable and interesting links.
Joyk means Joy of geeK