Hooks have become a part of React relatively recently, but they already have a major impact on how developers solve various problems with state management and more. But to take full advantage of React hooks requires experience. But while there may be some truth to the saying “no pain, no gain”, it doesn’t mean that you have to be the one to suffer. Through my own experience with hooks, I was able to come up with a lot of React hooks best practices so that you can get it right from the start.

Hooks in React made their debut at the beginning of 2019 and quickly gained popularity among React developers. Thanks to hooks, one could create stateful components without JavaScript classes and extending the React.Component. Hooks made our code simpler, more concise and readable.

Getting rid of the classes made a lot of the boilerplate code disappear. For example, there is no longer a need to use the constructor and call super with props every time. There is also no need to bind methods or think about what this is at the moment.

When using hooks, it is worth remembering a few rules, so that the code works as expected and is understandable to others. In this article, I will tackle two of them – _useState _and useEffect.

React hooks best practices – basics

I hope you already know this one, but I must mention it: Hooks cannot be called conditionally. You cannot put them in loops or nested functions inside your component.

So what to do if you want to call a hook conditionally? Just put the condition inside your hook.

Why is this so important? Hooks can be called multiple times in a given component and React operations are based on the order in which they are called. Not following this would introduce bugs to your application and fatal errors.

Fortunately, there is an eslint plugin created by React team which enforces you to follow this rule. It is called eslint-plugin-react-hooks and you can find it on npm. If you use Create React App for your application, it is installed by default.

This plugin will work not only with React hooks but also with every custom hook. But for this to happen, you have to follow a specific convention – the hook name must start with use.

#developer stories #frontend #hooks #javascript #react

React hooks best practices, tips and trends
5.85 GEEK