type of hooks in react


In React, there are several types of built-in hooks to handle different behavior of the components. Here is a list of commonly used built-in hooks.

1. State Hooks:

  • ‘useState’: It is the most commonly used React Hook. It allows functional components to have state variables. It takes an initial state value as the argument and returns an array with two elements — the current state value and a function to update that state.
import React, { useState } from 'react';

function Counter() {
const [count, setCount] = useState(0);

const increment = () => {
setCount(count + 1);
};

return (
<div>
<p>Count: {count}</p>
<button onClick={increment}>Increment</button>
</div>
);
}
  • ‘useReducer’: Provides an alternative to ‘useState’ for managing complex state logic involving multiple sub-values or when the next state depends on the previous one.
import React, { useReducer } from 'react';

const initialState = { count: 0 };

function reducer(state, action) {
switch (action.type) {
case 'increment':
return { count: state.count + 1 };
case 'decrement':
return { count: state.count - 1 };
case 'reset':
return initialState;
default:
throw new Error('Unsupported action type');
}
}

function Counter() {
const [state, dispatch] = useReducer(reducer, initialState);

const increment = () => {
dispatch({ type: 'increment' });
};

const decrement = () => {
dispatch({ type: 'decrement' });
};

const reset = () => {
dispatch({ type: 'reset' });
};

return (
<div>
<p>Count: {state.count}</p>
<button onClick={increment}>Increment</button>
<button onClick={decrement}>Decrement</button>
<button onClick={reset}>Reset</button>
</div>
);
}

2. Effect Hooks:

  • ‘useEffect’: It enables performing side effects, such as data fetching, subscriptions, or DOM manipulations after the component has been rendered.
import React, { useState, useEffect } from 'react';

function Example() {
const [data, setData] = useState(null);

useEffect(() => {
// This effect runs after the component has rendered

// Perform some asynchronous data fetching
fetchData()
.then((result) => {
setData(result);
})
.catch((error) => {
console.error('Error fetching data:', error);
});

// Clean up the effect
return () => {
// Perform any necessary cleanup here
// This is optional but important to prevent memory leaks
};
}, []); // Empty dependency array, so the effect runs only once on component mount

return <div>{data ? <p>Data: {data}</p> : <p>Loading data...</p>}</div>;
}

export default Example;
  • ‘useLayoutEffect’: Similar to ‘useEffect’, but runs synchronously after all DOM mutations are applied, useful for measuring layout or performing DOM manipulations that require synchronous updates.
import React, { useState, useLayoutEffect } from 'react';

function Example() {
const [width, setWidth] = useState(0);

useLayoutEffect(() => {
// This effect runs synchronously after all DOM mutations
// but before the browser paints

const updateWidth = () => {
const newWidth = document.documentElement.clientWidth;
setWidth(newWidth);
};

// Add event listener for window resize
window.addEventListener('resize', updateWidth);

// Initial width update
updateWidth();

// Clean up the effect
return () => {
// Remove event listener
window.removeEventListener('resize', updateWidth);
};
}, []); // Empty dependency array, so the effect runs only once on component mount

return <div>Window width: {width}px</div>;
}

export default Example;
  • ‘useEffectOnce’: A custom hook that runs an effect only once when the component mounts.
import React, { useEffect } from 'react';

function useEffectOnce(effect) {
useEffect(effect, []);
}

// Usage:
function Example() {
useEffectOnce(() => {
// This effect runs only once on component mount
console.log('Effect ran only once');
});

return <div>Example Component</div>;
}

export default Example;

3. Context Hooks:

  • ‘useContext’: This hook in React is used to consume values from a React context. It allows functional components to access the value provided by a context provider higher up in the component tree without the need for prop drilling.
  1. Create a context
// createContext.js
import React from 'react';

// Create a new context
const MyContext = React.createContext();

export default MyContext;

2. Provide a value using Context Provider

import React from 'react';
import MyContext from './createContext';

function App() {
const value = 'Hello, Context!';

return (
<MyContext.Provider value={value}>
<ChildComponent />
</MyContext.Provider>
);
}

3. Consume the context value using ‘useContext’

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

function ChildComponent() {
const contextValue = useContext(MyContext);

return <div>{contextValue}</div>;
}

4. Ref Hooks:

  • ‘useRef’: Provides a way to create mutable references to values or DOM elements that persist across renders. Often used for accessing or manipulating DOM elements.
import React, { useRef } from 'react';

function Example() {
const inputRef = useRef(null);

const handleClick = () => {
inputRef.current.focus();
};

return (
<div>
<input type="text" ref={inputRef} />
<button onClick={handleClick}>Focus Input</button>
</div>
);
}

export default Example;

5. Callback Hooks:

  • useCallback’: Memoizes a callback function, preventing it from being recreated on every render if the dependencies remain unchanged. Useful for optimizing performance by avoiding unnecessary re-renders of child components.
‘useCallback’: Memoizes a callback function, preventing it from being recreated on every render if the dependencies remain unchanged. Useful for optimizing performance by avoiding unnecessary re-renders of child components.‘useCallback’: Memoizes a callback function, preventing it from being recreated on every render if the dependencies remain unchanged. Useful for optimizing performance by avoiding unnecessary re-renders of child components.import React, { useState, useCallback } from 'react';

function Example() {
const [count, setCount] = useState(0);

const increment = useCallback(() => {
setCount(count + 1);
}, [count]);

return (
<div>
<p>Count: {count}</p>
<button onClick={increment}>Increment</button>
</div>
);
}

export default Example;
  • ‘useMemo’: It memoizes a value, preventing it from being recomputed on every render if the dependencies remain unchanged. It’s useful for optimizing expensive calculations or complex data transformations.
import React, { useState, useMemo } from 'react';

function Example() {
const [count, setCount] = useState(0);

const doubleCount = useMemo(() => {
return count * 2;
}, [count]);

return (
<div>
<p>Count: {count}</p>
<p>Double Count: {doubleCount}</p>
<button onClick={() => setCount(count + 1)}>Increment</button>
</div>
);
}

export default Example;

6. Layout Hooks:

  • ‘useDimensions’: It measures the dimensions of an element.
  • ‘useWindowSize’: It retrieves the current window size.

7. Form Hooks:

  • ‘useForm’: It provides form state and validation helpers.

8. Animation Hooks:

  • useSprings’: Creates animated values for animation using React Spring.

9. Custom Hooks:

  • You can create your own custom hooks to encapsulate reusable logic and stateful behavior. Custom hooks should follow the naming convention of starting with “use” to ensure they can leverage other hooks.

Comments