Optionally control state from parent component in React

useFallbackState

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.

useState

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

useFallbackState example

--

--

Get the Medium app

A button that says 'Download on the App Store', and if clicked it will lead you to the iOS App store
A button that says 'Get it on, Google Play', and if clicked it will lead you to the Google Play store