Redux is awesome for state management with React. It is based on the Flux pattern.
Let's take an example. Let's say we have a component with two children. How does one child component update the other? Or even, how does a child update the parent component in the first place? It's pretty easy for the parent to update the child (props) so the hard part is really just getting the info from the child to the parent. Here's the solution with vanilla React.
import React from 'react'
class Parent extends React.Component {
constructor(props) {
super(props)
this.state = {
count: 1
}
}
const updateCount = () => {
this.setState({count: this.state.count + 1})
}
render() {
return() {
<Child increment=this.updateCount />
}
}
}
class Child extends React.Component {
constructor(props) {
super(props)
}
render() {
return() {
<Button onClick=this.props.increment>Increment</Button>
}
}
}
The parent basically passes in a callback to the child, so that the child can call that function when changing the state. In this example, this is very doable. However, what happens when you have more components, nested more deeply in a complicated structure, with a lot more state to keep track of? Wouldn't it be nice to have a global state for your application?
Redux is NOT a replacement for React state and props. Moving every state variable to the redux store would very quickly become confusing and bloated. Redux should be used only for state that is accessed and mutated across many components, or between components that don't share a close relationship.
One of the main principles of React is that components are pure functions of the state and the props of that component, meaning that the same state and props should result in the component rendering in an identical way. If we have a global state, does it break this pattern? Does it mean every time we update the redux state, every component needs to re-render? The short answer is no: if this were the case, no one would use redux, as it would make React slow and useless.
There are two functions a developer should implement that allow us to connect a component to the redux state, and not every component needs to be connected. mapStateToProps
allows the developer to pick which pieces of the state the component depends on, and set them as props for the function. This way, we are accessing the redux state through props, and only the pieces of the state we use will cause the component to re-render. mapDispatchToProps
passes in the actions we want to perform on the redux state in the component. This is how we can update the redux state. When exporting the component, simply export connect(mapStateToProps, mapDispatchToProps)(Component)
rather than export Component
.