1.0.2 • Published 3 years ago

usehandlestate v1.0.2

Weekly downloads
-
License
ISC
Repository
github
Last release
3 years ago

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

  1. Install it using npm or yarn
    • npm install --save usehandlestate
    • yarn add usehandlestate
  2. Import it on your js file.
    • import useHandleState from 'usehandlestate'
  3. 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}

That's all folks 😎

1.0.2

3 years ago

1.0.1

3 years ago

1.0.0

3 years ago