ReactJS Hooks


In this tutorial, we are going to learn about React Hooks, their rules and commonly used hooks.

What are React Hooks?

React Hooks are functions that allow you to use state, lifecycle methods, and other React features in functional components. Prior to Hooks, these features were only available in class components. With Hooks, you can now write fully-featured components using functions, making your code more concise and easier to understand.


What are the Different Rules of Hooks?

When using Hooks, there are a few important rules to keep in mind:

  1. Hooks can only be used inside functional components or other custom hooks. They cannot be used in regular JavaScript functions or class components.
  2. Hooks must always be called at the top level of the component. They should not be called inside loops, conditions, or nested functions.
  3. Hooks should have consistent order. This means that you should call hooks in the same order every time the component renders. This helps React keep track of the state between renders.

What are the Commonly Used Hooks?

1. useState

  • The useState hook allows you to add state to your functional components.
  • It takes an initial state value as a parameter and returns an array with the current state value and a function to update that state.
  • You can use array destructuring to assign names to the state value and the state update function.

2. useEffect

  • The useEffect hook allows you to perform side effects in your components.
  • It replaces lifecycle methods like componentDidMount, componentDidUpdate, and componentWillUnmount.
  • You provide a function as the first parameter, which will be executed after each render.
  • Optionally, you can provide a second parameter (dependency array) that specifies which values should trigger the effect. If the dependency array is empty, the effect will run only once.

3. useContext

  • The useContext hook allows you to consume values from a Context provider in your functional components.
  • You need to pass the Context object created by React.createContext as a parameter to useContext.
  • It returns the current value provided by the nearest Context.Provider up the component tree

4. useRef

  • The useRef hook returns a mutable ref object that can hold a value across renders.
  • It is useful for accessing DOM elements or storing mutable values that persist between renders.

5. useMemo

  • The useMemo hook memoizes a value, preventing unnecessary calculations and re-rendering.
  • It takes a function and an array of dependencies as parameters and returns the memoized value.
  • The memoized value will only be recalculated if any of the dependencies change.

6. useCallback

  • The useCallback hook memoizes a function, preventing unnecessary re-creation of the function on each render.
  • It takes a function and an array of dependencies as parameters and returns the memoized function.
  • The memoized function will only be recalculated if any of the dependencies change.

7. useReducer

  • The useReducer hook is an alternative to useState when managing more complex state transitions.
  • It takes a reducer function and an initial state as parameters and returns the current state and a dispatch function.
  • The reducer function specifies how the state should be updated based on the dispatched action.

8. useParams

  • The useParams hook allows you to access the parameters from the current route in React Router.
  • It returns an object containing key-value pairs of the URL parameters.

9. useHistory

  • The useHistory hook gives you access to the history object in React Router.
  • It allows you to programmatically navigate, go back, or go forward in the browser's history.

10. useLocation

  • The useLocation hook gives you access to the current location object in React Router.
  • It provides information about the current URL, such as the pathname, search, and state.

11. useRouterMatch

  • The useRouterMatch hook provides access to the route matching information in React Router.
  • It returns an object containing properties such as path, url, params, and isExact.

12. useNavigate

  • The useNavigate hook allows you to programmatically navigate in React Router v6.
  • It returns a navigate function that you can use to navigate to a specific location.

13. useCustom (Custom Hook)

  • Custom Hooks allow you to extract reusable logic into separate functions.
  • You can create your own custom hooks by combining existing hooks or creating new functionality.
  • Custom Hooks should be prefixed with "use" to follow the conventions of React Hooks.

FAQs

While React Hooks offer a more concise and functional approach to state and lifecycle management, they are not a direct replacement for class components. Class components are still fully supported and will continue to be part of React. Hooks provide an alternative and more modern way to work with stateful logic in functional components.

Yes, you can use multiple Hooks in a single component. React encourages the use of Hooks as building blocks for different functionalities. You can use as many Hooks as needed in a component, making it more modular and easier to maintain.

Side effects, such as fetching data from an API or interacting with the browser's DOM, can be handled using the useEffect Hook. The useEffect Hook allows you to perform side effects after the component has rendered or when certain dependencies have changed. This helps in managing the component's lifecycle and preventing issues related to asynchronous operations.