I
I
Ilya2019-10-13 13:27:07
React
Ilya, 2019-10-13 13:27:07

What is the best way to take out the logic of the counter: a separate component or a custom hook?

In the cart, each product has a “counter”: a quantity field with the “Decrease” and “Increase” buttons.
I want to take this logic out of the main component. What is the best way to do this: a separate component or a custom hook ?
Link sandboxes. I tend to the option with the component: this way the code seems better. Please write what you think. If you still tell me how to refactor something, I will also be grateful.

Answer the question

In order to leave comments, you need to log in

1 answer(s)
A
abberati, 2019-10-13
@sidorchik

The first option is definitely better, since the parent now does not know about the implementation of children. But why don't you encapsulate the logic inside Counter in a custom hook? It will be used only by the Counter component, so the code will be even cleaner - the parent does not know about the implementation of children, the Counter component is simple, and the internal logic of this component is described inside a custom hook.
Regarding “do better”: make two state variables inside the app and pass your [countN, setCountN] to each counter - why do counters need to know about other counters? Then there will be less code inside the counter - you need to process data for this particular counter, without having to do setValues({ ...values, })

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question