By WalkingTree November 04, 2020
React features such as state and lifecycle functions were only limited to class-based components. With React Hooks, Function-based components have hugely benefited. Hooks has enabled function components to compose, reuse, and share React code in new ways. Let’s take a look at some of the tips for implementing Hooks in your components.
- Follow the rules of Hooks – It’s best to follow all the rules of Hooks. Some of the common rules include:
- Only call Hooks at the top level: Don’t call hooks inside loops and conditions. When you want to use hooks conditionally, write the condition inside those hooks.
- Create your function components in the right order – When you create class components, there is a certain order which has to be followed to maintain and improve the React application code. Firstly, call the constructor and initiate your state. Then, write the lifecycle functions. Finally, write the render method.
- Use custom hooks for sharing application logic – As you keep building your application, you will notice that some of your application logic will be used numerous times across many components. With React Hooks, you can extract your component’s logic into reusable functions as custom hooks.
- Avoid prop drilling with useContext – Prop drilling is a common problem in React applications where you pass data down from one parent component through the component layers. React Context is a feature that provides a way to pass data down through the component tree without needing to pass props manually between components. useContext hook can be used to define the value of React Context in the parent component.
- ESLint plugin for React hooks – The React team has created an ESLint plugin named eslint-plugin-react-hooks to help write Hooks the right way in their projects. This plugin will help in fixing hooks errors before even you try to run the application.
Read on to know more about React Hooks and its best practices.
This blog is dedicated to yet another useful React hook “useReducer” in continuation to my previous blog, and…
React Hooks are the latest additions to the React block (React version 16.8) as they bring along great…
There is a favourite quote among social scientists that says, “It takes a village to raise a child”….