Skip to main content

Hooks

1. Introduction to Hooks

React Hooks introduced in React 16.8 provide a more functional approach to managing state and side effects in functional components. This section provides guidelines for using hooks effectively in your React applications.

2. Using Hooks

Hooks enable functional components to manage state and side effects. Follow these guidelines when using hooks:

Do

  • Do use hooks to manage state, side effects, and lifecycle methods in functional components.
  • Do follow the rules of hooks. Only call hooks at the top level of your component or custom hook.
  • Do use built-in hooks like useState, useEffect, useContext, etc., provided by React.
  • Do name custom hooks with the use prefix (e.g., useCustomHook) to indicate that it's a hook.

Do Not

  • Do Not use hooks inside loops, conditions, or nested functions. Hooks should always be called at the top level of your components.
  • Do Not call hooks conditionally. Hooks should be called in the same order on every render.
  • Do Not define hooks inside regular JavaScript functions. Hooks should only be called in React functional components or custom hooks.

3. useState Hook

The useState hook allows functional components to manage local state. Follow these guidelines when using the useState hook:

Do

  • Do use useState to manage local component state.
  • Do destructure the state variable and update function when using useState.

Do Not

  • Do Not mutate state directly. Always use the updater function provided by useState to update state.

4. useEffect Hook

The useEffect hook enables performing side effects in functional components. Follow these guidelines when using the useEffect hook:

Do

  • Do use useEffect for data fetching, subscriptions, or manually changing the DOM.
  • Do clean up side effects using the cleanup function returned by useEffect when necessary.

Do Not

  • Do Not forget to specify dependencies in the dependency array of useEffect. This ensures that the effect is only re-run when necessary.

5. useContext Hook

The useContext hook allows functional components to consume context provided by a React.Context component. Follow these guidelines when using the useContext hook:

Do

  • Do use useContext to consume context within functional components.

Do Not

  • Do Not use useContext inside deeply nested components where it's not necessary. Pass down props instead if possible.

6. Custom Hooks

Custom hooks allow you to extract reusable logic from components. Follow these guidelines when creating custom hooks:

Do

  • Do create custom hooks to share reusable logic between components.
  • Do name custom hooks with the use prefix to indicate that it's a hook.

Do Not

  • Do Not create custom hooks for every small piece of logic. Only create custom hooks for logic that is used in multiple components.

These guidelines will help you use hooks effectively in your React applications, leading to cleaner and more maintainable code.