Know about react hooks?

deepak chandra
2 min readFeb 17, 2023

--

React Hooks are a new feature introduced in React 16.8 that allow you to use state and other React features in functional components.

The most commonly used React Hooks are:

  1. useState: allows you to add state to functional components. It takes an initial value as a parameter and returns an array containing the current state value and a function to update that value.

Example:

import React, { useState } from 'react';
function MyComponent() {
const [count, setCount] = useState(0);
return (
<div>
<p>You clicked {count} times</p>
<button onClick={() => setCount(count + 1)}>
Click me
</button>
</div>
);
}
  1. useEffect: allows you to add side effects to functional components. It takes a function as a parameter that will be executed after every render. You can also provide a second parameter, which is an array of dependencies that the effect depends on. If any of the dependencies change, the effect will be re-executed.

Example:

import React, { useState, useEffect } from 'react';
function MyComponent() {
const [count, setCount] = useState(0);
useEffect(() => {
document.title = `You clicked ${count} times`;
}, [count]);
return (
<div>
<p>You clicked {count} times</p>
<button onClick={() => setCount(count + 1)}>
Click me
</button>
</div>
);
}
  1. useContext: allows you to consume a context object created by the React.createContext() function. It takes a context object as a parameter and returns the current value of that context.

Example:

import React, { useContext } from 'react';
import MyContext from './MyContext';

function MyComponent() {
const value = useContext(MyContext);
  return (
<div>
<p>Value from context: {value}</p>
</div>
);
}

There are many other Hooks, such as useReducer, useCallback, useRef, useMemo, and more. You can also create your own custom Hooks to reuse stateful logic across multiple components.

--

--

deepak chandra
deepak chandra

Written by deepak chandra

I am a developer and designer from India🇮🇳. I have a passion for programming and designing. I'd call myself a Jack of all trades but master of none.

No responses yet