Home > Software design >  How to sync two counters in React js using hooks?
How to sync two counters in React js using hooks?

Time:12-08

I am new to react js, I want to connect two counters in React js, As if one counter value gets increased by one the other counter value should get decreased by one, And on the button click, I need to add a new set of counter pairs. Can anyone suggest to me a solution? Thank you.

CodePudding user response:

If you want to create a counter pair and have to do it multiple times, I would suggest to use custom Hooks.

I have created one for the purpose named useCounter.

Here you have to pass an array of length 2 if initial state of counter. And the hook will return [couters, updateCounter, err] the array.

You can refer to this code for insight.

Hook: https://codesandbox.io/s/happy-swartz-ikqdn?file=/src/counterHook.js

Component using hook: https://codesandbox.io/s/happy-swartz-ikqdn?file=/src/pair.js

Note: goto https://ikqdn.csb.app/pair in codesandbox browser

  • Related