Know about react hooks?
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:
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>
);
}
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>
);
}
useContext
: allows you to consume a context object created by theReact.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.