HOME C C++ PYTHON JAVA HTML CSS JAVASCRIPT BOOTSTRAP JQUERY REACT PHP SQL AJAX JSON DATA SCIENCE AI

React Custom Hooks

React Custom Hooks

custom hooks are functions that encapsulate reusable logic.

They allow you to extract and share stateful logic between components. Custom hooks should start with the word "use" to follow the convention.

Here's a simple example of a custom hook that manages the state of a toggle:

import { useState } from 'react';

const useToggle = (initialState = false) => {
const [state, setState] = useState(initialState);

const toggle = () => {
setState((prevState) => !prevState);
};

return [state, toggle];
};

export default useToggle;

Now, you can use this custom hook in your components:

import React from 'react';
import useToggle from './useToggle';

const MyComponent = () => {
const [isToggled, toggle] = useToggle(false);

return (
<div>
<p>Is Toggled: {isToggled ? 'Yes' : 'No'} </p>
<button onClick={toggle}>Toggle </button>
</div>
);
};

export default MyComponent;

In this example, the 'useToggle' hook returns an array with two elements: the current state ('isToggled') and a function to toggle the state ('toggle'). The custom hook encapsulates the logic related to toggling, and you can reuse it in multiple components.