Skip to content

Instantly share code, notes, and snippets.

@abel-masila
Last active September 10, 2018 12:42
Show Gist options
  • Save abel-masila/bf43070540956c62c202ca052579c7e6 to your computer and use it in GitHub Desktop.
Save abel-masila/bf43070540956c62c202ca052579c7e6 to your computer and use it in GitHub Desktop.
Redux is a state container to keep your state in one place...single source of truth.
But initially, youd don't need redux until your app grows and you can't track tell the source of the props in some of the components.
we have components for a name input, a name list, and after the name list generates the pairs which are then displayed in the pairs container.
But here’s the problem(s):
-[X] How does NameInput send the name into the NameList?
-[X] How does NameList have access to the names?
-[X] How does PairContainer know what the pairs are?
Essentially, how do my components communicate with each other?
We can easily envision a solution where a higher level component, something named NameContainer or NameApp would hold the state of the data in it’s local state and we can have out lower level components inherit callbacks and data from it, like this:
export default class NameContainer extends Component {
constructor(){
this.state = {
names: []
}
}
changeState(event){
this.setState({
names: [...this.state.names, event.target.value]
})
}
render(){
return (
<div>
<NameInput handleSubmit={this.changeState}/>
<NameList names={this.state.names} />
</div>
)
}
Note: The above is not actually implemented code, just a possible way to get the components to talk to each other.
This can work for a few components and in this case it is probably the best solution. Buuuuuuuut….
The Problem With The Solution
What if we have a whole bunch of components that make similar changes to this higher lever component?
Also, what if we wanted to change a different part of the state, like the pairs?
What’s going to happen in that the state will no longer be coherent because each component doesn’t really understand what the other components are doing and therefore are not aware of what changed since they decided that they wanted to change it.
The Solution
Redux offers a single container for our entire App’s state which ensures that we don’t have to deal with the mess that I described above.
Redux is a predictable state container for JavaScript apps.
With Redux we initialize a store for our entire app, this keeps state and reducers which modify that state in a very specific way, making sure that we can keep track of every change.
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment