REACT HOOKS.


What is a Hook?

Hooks are basically used to replace class-based components and use class-related features without actually using them. React Hooks are simple JavaScript functions that we can use to set apart the reusable part from a functional component. Hooks can be stateful and can manage side effects.

React Built−in Hooks.

React has various built−in hooks, but mainly used are:- ( useEffect ) and ( useState ).

  1. useState Hook

The useState hook is used for storing a state within a component.The useState hook allows you to store and access state inside a component without using this.state or this.setState(). The state object can be passed down from the parent component to the child component via props, or it can be set directly on the child component with the useState hook. Let us understand this with the help of a example:-

In the above example we created a arrow function (App) and assigned the useState hook to it….Now the default value in useState is given in the text reflected in green. If the user makes any changes in the element to which (setMssg) is assigned the value will be changed automatically in mssg.

2. useEffect Hook

For side effects like obtaining data from an API or storing it locally, we use useEffect hook.

It gives function components the ability to perform side effects, resulting in accomplishing the same thing that componentDidMount, componentDidUpdate, and componentWillUnmount do in React classes, but with a single API.

React also offers a number of other Built-in Hooks which can be used by the user according to his usage and needs.

Various Other Hooks:-

1. useContext Hook:- It can be used together with the useState Hook to share state between deeply nested components more easily than with useState alone.

2. useRef Hook:- The useRef Hook allows you to persist values between renders. It can be used to store a mutable value that does not cause a re-render when updated.

3. useReducer Hook:- The useReducer Hook is similar to the useState Hook. It allows for custom state logic. The useReducer Hook accepts two arguments.

4. useCallback Hook:- This allows us to isolate resource intensive functions so that they will not automatically run on every render.

Despite so many hooks, Mainly used hooks are useState and useEffect.

<————————————————————————————–>


Leave a Reply

Your email address will not be published. Required fields are marked *