DEV Community

Cover image for Hooks in React
M.Ark
M.Ark

Posted on • Edited on

Hooks in React

Hooks are functions that let you use React features. All hooks are recognizable by the use prefix. For example, useState is a hook.

React Hooks are functions that let you use state and other React features in functional components.

Introduced in React 16.8, hooks provide a way to manage component logic in a more concise and reusable way compared to class components.

For now, remember that hooks have rules that we need to abide by:

Hooks can only be called from the top level of a functional component.
Hooks can’t be called from inside loops or conditions.

Commonly Used Hooks

  1. useState: Manages state within functional components.
  2. useEffect: Handles side effects like data fetching, subscriptions, or manually changing the DOM.
  3. useContext: Provides a way to use React's Context API in functional components.
  4. useReducer: Manages complex state logic and is an alternative to useState.
  5. useRef: Accesses DOM elements directly or persists mutable values across renders.
  6. useMemo: Memoizes expensive calculations.
  7. useCallback: Memoizes callback functions to prevent unnecessary re-renders.
  8. useLayoutEffect: Similar to useEffect, but it fires synchronously after all DOM mutations.
  9. useImperativeHandle: Customizes the instance value that is exposed when using ref in parent components.

Well go through afew of the hooks.

  1. useState: Manages state within functional components.

Image description

In the example above; 'useState' initializes state and returns an array with the current state value and a function to update it.

  1. useEffect: Handles side effects like data fetching, subscriptions, or manually changing the DOM.

Image description
The example above is a section of the useEffect in a react file when collecting data.Here is how the whole file with the use Effectlooks like.

Image description
These are the most used hooks in react.

Lets dive and learn more on useState here.

Top comments (0)