Control Props, I
Summary: The control props pattern lets the user of a component manage that components state from the outside. Write a very simple button component that implements the bare minimum of this pattern.
Create a very simple component that has a button you can click and also displays its internal state with an initial state of {count: 0}
. By default, the button increments its count by one when it is clicked. This component should be controllable from the outside, so that the user could control how the state is updated each time the component is clicked.
Say from the outside say you want to use this same button but instead:
- The counter starts at
{count: 1
} - You'd rather double the value at each click.
- You also want to display: the previous count value, the suggested value, and the count value that would have happened if we weren't controlling this component.
- You might also want the button to reset when it reaches a particular maximum value.
Here's an example api of how might want to use it. Whenever the state of the component changes, it will pass the suggestedState
and the action
that happened. And you can do whatever you want with that information to get the new state which you will pass back to the component.
My Solution
Your component MyButtonWithStateDisplay
could be using a hook useMyButtonWithStateDisplay
like this. It uses the prop collections pattern!
The hook is responsible for returning the actual state
and the props that you should pass to the button given
the optional onChange
handler and controlled state
passed to the component if any.
And your useMyButtonWithStateDisplay
hook may be using a reducer like this:
What we want the hook to do:
The hook should return the new
state
of this component and thebuttonProps
that the component passes to its button. ThebuttonProps
contains the props that the button needs, so that the behavior we want will be executedonClick
.If we don't pass a
controlledState
,onClick
will do the default behavior. WhencontrolledState
is passed to it,onClick
will execute theonChange
function, by passing thesuggestedChange
(default behavior result) and theaction
that happened to thisonChange
function.
Here's how we could write the hook: