Hooks in React
M.Ark
Posted on June 19, 2024
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
- useState: Manages state within functional components.
- useEffect: Handles side effects like data fetching, subscriptions, or manually changing the DOM.
- useContext: Provides a way to use React's Context API in functional components.
- useReducer: Manages complex state logic and is an alternative to useState.
- useRef: Accesses DOM elements directly or persists mutable values across renders.
- useMemo: Memoizes expensive calculations.
- useCallback: Memoizes callback functions to prevent unnecessary re-renders.
- useLayoutEffect: Similar to useEffect, but it fires synchronously after all DOM mutations.
- useImperativeHandle: Customizes the instance value that is exposed when using ref in parent components.
Well go through afew of the hooks.
- useState: Manages state within functional components.
In the example above; 'useState' initializes state and returns an array with the current state value and a function to update it.
- useEffect: Handles side effects like data fetching, subscriptions, or manually changing the DOM.
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.
These are the most used hooks in react.
Lets dive and learn more on useState here.
Posted on June 19, 2024
Join Our Newsletter. No Spam, Only the good stuff.
Sign up to receive the latest update from our blog.