Common React Hooks Mistakes You Should Avoid

5 Common mistakes to avoid when using react hooksReact 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, som…


This content originally appeared on Bits and Pieces - Medium and was authored by Piumi Liyana Gunawardhana

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.

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 !!!

Learn More


Common React Hooks Mistakes You Should Avoid was originally published in Bits and Pieces on Medium, where people are continuing the conversation by highlighting and responding to this story.


This content originally appeared on Bits and Pieces - Medium and was authored by Piumi Liyana Gunawardhana


Print Share Comment Cite Upload Translate Updates
APA

Piumi Liyana Gunawardhana | Sciencx (2021-11-01T16:46:54+00:00) Common React Hooks Mistakes You Should Avoid. Retrieved from https://www.scien.cx/2021/11/01/common-react-hooks-mistakes-you-should-avoid/

MLA
" » Common React Hooks Mistakes You Should Avoid." Piumi Liyana Gunawardhana | Sciencx - Monday November 1, 2021, https://www.scien.cx/2021/11/01/common-react-hooks-mistakes-you-should-avoid/
HARVARD
Piumi Liyana Gunawardhana | Sciencx Monday November 1, 2021 » Common React Hooks Mistakes You Should Avoid., viewed ,<https://www.scien.cx/2021/11/01/common-react-hooks-mistakes-you-should-avoid/>
VANCOUVER
Piumi Liyana Gunawardhana | Sciencx - » Common React Hooks Mistakes You Should Avoid. [Internet]. [Accessed ]. Available from: https://www.scien.cx/2021/11/01/common-react-hooks-mistakes-you-should-avoid/
CHICAGO
" » Common React Hooks Mistakes You Should Avoid." Piumi Liyana Gunawardhana | Sciencx - Accessed . https://www.scien.cx/2021/11/01/common-react-hooks-mistakes-you-should-avoid/
IEEE
" » Common React Hooks Mistakes You Should Avoid." Piumi Liyana Gunawardhana | Sciencx [Online]. Available: https://www.scien.cx/2021/11/01/common-react-hooks-mistakes-you-should-avoid/. [Accessed: ]
rf:citation
» Common React Hooks Mistakes You Should Avoid | Piumi Liyana Gunawardhana | Sciencx | https://www.scien.cx/2021/11/01/common-react-hooks-mistakes-you-should-avoid/ |

Please log in to upload a file.




There are no updates yet.
Click the Upload button above to add an update.

You must be logged in to translate posts. Please log in or register.