Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Where to store the state to make React components more reusable

I have an autocomplete component which has following props:

  • value (display text),
  • onChange (fired on every keystroke)
  • onSelect(fired when user picks something from the list of
    suggestions, passes selected object + display text of selected object - the same as value)

state: - suggestionsList (I've decided it's a state as it's something internal to the component).

On one of the views parent of this component doesn't care about the value after each keystroke. It just cares about the selected item passed by onSelect handler. So in this scenario value & onChange props are not needed. value could become an internal state of the autocomplete component.

But on one of the other views parent would like to also know about each keystrokes. This means the parent would need to hold the value in his state and also pass it as props. onChange props would be also needed to notify parent to change its state.

How to construct the autocomplete component so it handles both scenarios? Which properties should be props and which state?

Any suggestions appreciated.

like image 365
mbudnik Avatar asked Dec 05 '25 20:12

mbudnik


1 Answers

In the second case, if the parent needs to know about the current value, it doesn't need to hold the variable, so I guess that if you pass the current value (from an internal state variable) as a parameter to the onChange prop function, the parent will notice the change and update accordingly.

Another way to do it is to use the value property and a internal state variable. What I mean is: if the parent wishes to control the value it will have an state entry for it and will be responsible for updating it, in other case the value property must not be provided because it would end as a constant. Your component will use this property as the current value every time its provided, and the parent should use onChange to update the va;ue that it holds.

You can check the source code of the auto complete component in material-ui.

like image 61
Rolando Urquiza Avatar answered Dec 08 '25 10:12

Rolando Urquiza



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!