React Custom Hook
Last update: 2023-01-10Type
Quick Win
Membership
🆓
Tech
React
To extract code into a custom React hook, follow these steps:
- Identify a piece of stateful logic in your component that you would like to extract into a hook.
- Create a new JavaScript function with the name starting with “use” (e.g.,
useMyHook
) - Move the stateful logic into the new hook.
- Replace calls to setState with
setStateVariable
wherestateVariable
is the state variable you want to update. - 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.