Need help with use-state-with-callback?
Click the “chat” button below for chat support from the developer who created it, or find similar developers for support.

About the developer

the-road-to-learn-react
140 Stars 19 Forks MIT License 20 Commits 11 Opened issues

Description

Custom hook to include a callback function for useState.

Services available

!
?

Need anything else?

Contributors list

useStateWithCallback React Hook

Build Status Slack Greenkeeper badge Coverage Status NPM

Custom hook to include a callback function for useState which was previously available for setState in class components. Read more about it here.

Installation

npm install use-state-with-callback

Usage

useStateWithCallback:

import React from 'react';

import useStateWithCallback from 'use-state-with-callback';

// Note: cannot be used on the server-side (e.g. Next.js) // import { useStateWithCallbackInstant } from 'use-state-with-callback';

const App = () => { const [count, setCount] = useStateWithCallback(0, count => { if (count > 1) { console.log('render, then callback.'); console.log('otherwise use useStateWithCallbackInstant()'); } });

// const [count, setCount] = useStateWithCallbackInstant(0, count => { // if (count > 1) { // console.log('render with instant callback.'); // } // });

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

return (

{count}

  <button type="button" onclick="{handleClick}">
    Increase
  </button>
</div>

); };

useStateWithCallbackLazy:

import React from 'react';
import { useStateWithCallbackLazy } from 'use-state-with-callback';

const App = () => { const [count, setCount] = useStateWithCallbackLazy(0);

const handleClick = () => { setCount(count + 1, (currentCount) => { if (currentCount > 1) { console.log('Threshold of over 1 reached.'); } else { console.log('No threshold reached.'); } }); };

return (

{count}

  <button type="button" onclick="{handleClick}">
    Increase
  </button>
</div>

); };

export default App;

Contribute

  • git clone [email protected]:the-road-to-learn-react/use-state-with-callback.git
  • cd use-state-with-callback
  • npm install
  • npm run test

More

We use cookies. If you continue to browse the site, you agree to the use of cookies. For more information on our use of cookies please see our Privacy Policy.