React Custom Hook

Last update: 2023-01-10
Type
Quick Win's logo Quick Win
Membership
🆓
Tech
React React
React
Share:

To extract code into a custom React hook, follow these steps:

  1. Identify a piece of stateful logic in your component that you would like to extract into a hook.
  2. Create a new JavaScript function with the name starting with “use” (e.g., useMyHook)
  3. Move the stateful logic into the new hook.
  4. Replace calls to setState with setStateVariable where stateVariable is the state variable you want to update.
  5. Return the state variable(s) and update function(s) from the hook.

Here’s an example of a component with stateful logic:

import React, { useState } from 'react';

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

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

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

And here’s the equivalent code after moving the stateful logic into a custom hook:

import React, { useState } from 'react';

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

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

	return [count, incrementCount];
}

To use the new hook, simply call the hook function within your component, like this:

function ExampleComponent() {
	const [count, incrementCount] = useCount();

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

Now, you can reuse the useCount hook in other components, keeping your code clean and modular.

Simon Grimm