Build a Controlled and Uncontrolled Component with React
/ 4 min read
In the previous post we have learned about controlled and uncontrolled component, and also the difference between those two.
In this post we’re going to build a component that supports both controlled and uncontrolled mode from scratch.
Let’s get started by building a 5-star rating component.
Here’s what we’re going to do:
- We build the controlled and uncontrolled version of Rating component separately.
- Then we combine them into one component that support controlled and uncontrolled mode.
Controlled Rating component
Building a component in controlled mode should be familiar to those who have been learning React for a couple weeks.
We’re using the good old React props, nothing fancy about this code.
Here’s how we can use this component from our app.
The app is responsible for managing the displayed rating.
Uncontrolled Rating component
Let’s see how we build this uncontrolled Rating component.
Here’s how it’s different compared to the previous controlled implementation:
- We maintain the rating value of the component using an internal state.
- When the star is clicked, we set the rating state to the desired value.
This is how we use the uncontrolled component.
Combining them together
Now let’s combine those two components above into a single Rating component that supports both controlled and uncontrolled mode.
I will explain everything in the code comments so you can get better context.
And now we can use the component in both controlled and uncontrolled mode at the same time.
Try it for yourself
I’ve prepared this sandbox for you to try it yourself.
Notice that the controlled component causes re-render each time the rating changes, while the uncontrolled version doesn’t cause re-renders at all.
This is why I prefer to use uncontrolled components by default.