React Hooks

Karnika Gupta
Women in Technology
2 min readJun 22, 2023
React
React

React hooks is a feature introduced in React 16 that allows you to manage the state without having to write the class. Previously, functional components were limited to being stateless and could not handle local states or lifecycle methods but hooks provide a way to manage stateful logic. Some of the React hooks are “useState”, “useEffect”, “useMemo”, “useReducer”, “useContext”.

What is the use of hooks?

There are several reasons to use hooks. Some of them are listed below:

  1. State management: Hooks are introduced as a feature to manage the internal state in the functional component. Before hooks, the functional component in React was stateless. A react hook “useState” helps in managing the state by providing a state variable. It is an easy and quick way to deal with states in functional components.
  2. Code re-usability: Hooks promotes code re-usability as it allows you to share the stateful logic across multiple components without writing it multiple times. Custom hooks can be created to pass down the data to all the components that require it. This will avoid code duplication and helps in maintaining the code.
  3. Lifecycle events and side-effects: You can subscribe to events, fetch data, or perform other actions after the functional component has been rendered by using the “useEffect” hook. It helps in managing the side effects in an informative and centralized manner.
  4. Simplifying complex state logic: Hooks like “useReducer” provide a mechanism to manage complex state logic within functional components. They are useful when the state updates depend on the previous state. It is more like an alternative to “useState”.
  5. Improved readability and maintainability: The logic of the component is locally defined within the function which makes it less dependent on the other components. Hooks make your code easier to read, understand and maintain.
  6. Performance optimization: React hooks allow you to memoize values and optimize expensive calculations by preventing unnecessary re-renders. This can lead to improved performance and better user experience.

Rules and Guidelines for Using React Hooks

The rules are defined below:

  1. Only use hooks at the top level: Hooks should only be called at the top level of the functional component or within other hooks.
  2. Call hooks in the same order: The order of hooks matters because the state needs to be maintained between the renders.
  3. Conditional hooks: You cannot call hooks conditionally in your component function. You can use it inside a condition or sub-component.
  4. Custom hooks: Custom hooks should be prefixed with the word “use” to follow the convention.

--

--