I started my app without any state management dependencies and my app's state looked something like this:
state = { ...initState, } ///some actions I need to perform handleChange = (e) => { this.setState(setDefaultValues(e)); this.setState(setBmr); this.setState(setTdee); this.setState(setTrainingAndRestDaysCal); this.setState(setTrainingMacros); this.setState(setRestMacros); } here I import my initState from separate file (to save some space). Then I have handleChange where I'm passing functions to multiple this.setState because my next state data depends on previous. I'm importing those functions from separate file (to save some space as well)
Then I came to the point where I realized I'm passing props all over the place so I introduced the new react's context API. Which works very well in my opinion. Kind of like a redux just without a big boilerplate. So this context API helped me with that prop drilling through the child components. To use the context API i had to do some changes to my state object, so it looks like this now:
state = { ...initState, handleChange: (e) => { this.setState(setDefaultValues(e)); this.setState(setBmr); this.setState(setTdee); this.setState(setTrainingAndRestDaysCal); this.setState(setTrainingMacros); this.setState(setRestMacros); }, setTrainingTrueOrFalse: (isIt) => { this.setState({ trainingToday: !isIt }) }, saveNewMeal: (meal) => { const meals = this.state.meals this.setState({ meals: { ...meals, meal } }) } Here I added my handleChange to my state so I can pass it via context api. Then I have created some new functions on the state an realized my state now is getting too messy.
- I have a function on the state (handleChange ) that uses other functions imported from
setStateFunctions.js - I have functions where logic is not extracted to
setStateFunctions.js
On a high level my app has 2 main components: Calculator & MealPlanner
- Calculator - calculates the macros and calories and passes the result to MealPlanner
- MealPlanner - uses data from calculator and creates meals
==================================================
- What's the better approach to structure my app's state and functions?
- Do I really need to introduce
redux? - What would be my reducers structure?
- How would this look like using just react's new
context API?
setStatemultiple times in one event is anti-pattern. If you are looking for something light weight, tryMobX. It's easier thanRedux, you don't have to restructure your existing code.