DEV Community

subbiah chandru
subbiah chandru

Posted on

Optionally control state from parent component in React

Image description

useFallbackState is almost same as useState, but it takes 3 props instead of 1.

1st prop is the same -> default value.

2nd prop is the state from the parent. It's optional if parent doesn't send a prop then local useState's value will be used.

3rd prop is the setState from the parent. This callback will be called every time state changes.

Image description

In above code state's have been managed inside component.

Lets say this component is used in 10 places and you get a scenario where you need to manage the state from parent in just 1 place.

Now instead of adding if…else… condition in 100s of places you could simple replace useState to useFallbackState. Please see the example below.

Image description

Top comments (0)