I know there is now the Context API which should be used for global app state management.
But I am wondering, is there anything wrong (or not optimal) with managing the global state of the app using useState and passing into props like this?
//App.js
function App() {
const [counterA, setCounterA] = useState(0);
const [counterB, setCounterB] = useState(0);
let masterStates = {
counterA: counterA,
counterB: counterB,
}
let masterFunctions = {
setCounterA: setCounterA,
setCounterB: setCounterB,
}
return (
<div>
...
<ChildComponent masterStates={masterStates} masterFunctions={masterFunctions} />
...
</div>
)
}
Then in my ChildComponent, I can easily access the state and update it like this:
//ChildComponent.js
function ChildComponent(props) {
useEffect(() => {
console.log("This will successfully log when counterA changes: ", props.masterStates.counterA);
}, [props.masterStates.counterA]);
return(
<button onClick={() => props.masterFunctions.setCounterA(a => a + 1)}>
{props.masterStates.counterA}
</button>
)
}
Thanks for all the insightful comments! That really helped clear things up for me.
I was not familiar with this term "prop drilling" but now it makes a lot of sense.
I'm leaving here some useful links for anyone who would like to learn a little more about this:
https://kentcdodds.com/blog/prop-drilling
https://www.geeksforgeeks.org/what-is-prop-drilling-and-how-to-avoid-it/
https://medium.com/analytics-vidhya/props-drilling-in-react-js-934120a4906b
Edit: I just found this article here where he describes an approach like mine and lays out some of its benefits.
https://dev.to/bytebodger/rethinking-prop-drilling-state-management-in-react-1h61