What are hooks in react?
2 min readDec 2, 2023
- Hooks are introduced in React version 16.8, they are backward compatible
What are Hooks?
- Hooks are special JavaScript functions, however they are more restrictive than normal functions
- Hooks name normally start with
use
(e.g useState, useEffect etc.) - Possible to create custom hooks
- Hooks are JavaScript functions which maintains the state/data
- Hooks are special functions that are only available while React is rendering
Why Hooks?
- Hooks solved many different problems in the react.
- React doesn’t have an option to add reusable behavior to the component like connect to store.
- With hooks, we can extract stateful logic from component, so that component can be tested and reusable independently
- Using hooks, react component can be separated into stateless and stateful
- Stateless as a component used for rendering, and hooks are for stateful
- Refer official document for more details
Hooks restrictions:
- You can only call Hooks at the top of the components (or other Hooks).
- You can’t call Hooks inside conditions, loops, or other nested functions.
- Hook name start with
use
Some of the in-built hooks:
- useState:
- This is most popular and widely used hook.
- This is used to maintain state of the value
- This is used to updated/modify the state/data
import React, { useState } from 'react';
function UseStateHookExample() {
// Declare a new state variable, which we'll call "count"
const [count, setCount] = useState(0);
// remaining rendering code
}
- useEffect:
- The Effect Hook lets you perform side effects in function components
- This react hook will help in synchronizing component with external system
- If no external system involved, no need to use this hook
- Data fetching, setting up a subscription, and manually changing the DOM in React components are all examples of side effects.
import React, { useState, useEffect } from "react";
function UseEffectHookExample() {
const [count, setCount] = useState(0);
// Similar to componentDidMount and componentDidUpdate:
useEffect(() => {
// Update the document title using the browser API
document.title = `You clicked ${count} times`;
});
// remaining rendering code
return (
<div>
<p>You clicked {count} times</p>
<button onClick={() => setCount(count + 1)}>Click me</button>
</div>
);
}