1.0.2 • Published 3 years ago
usehandlestate v1.0.2
useHandleState
A simple React Hook that joins useState and useCallback.
Description: Sometimes you just need to create a state and a useCallback function to handle it. useHandleState lets you create both at the same time.
Example
without useHandleState:
import { useState } from 'react'
function Form(){
const [text, setText] = useState('');
const onTextChange = useCallback((e) => {
setText(e.target.value);
}, [setText]);
return (
<form>
<input value={text} onChange={onTextChange}>
</form>
)
}
with useHandleState:
import useHandleState from 'usehandlestate'
function Form(){
const [text, setText, onTextChange] = useHandleState('',
(e) => setText(e.target.value),
[setText]
);
return (
<form>
<input value={text} onChange={onTextChange}>
</form>
)
}
How to use
- Install it using npm or yarn
npm install --save usehandlestate
yarn add usehandlestate
- Import it on your js file.
import useHandleState from 'usehandlestate'
- Use it just like the useState hook, but you'll need to pass a useCallback function as the second parameter and the useCallback dependencies as the third paremeter. The useCallback function will be returned as the third array element.
// using useHandleState()
const [state, setState, handleState] = useHandleState(
{num: 0}, // default state
(newNum) => { setState({num: newNum}) }, // useCallback function
[setState] // useCallback dependencies
);
// handleState() fires the useCallback function
handleState(7) // set state as {num: 7}