npm install redux react-redux
Have central storage for data
Passing around props is bad
Define central store with redux
A component subscribes to changes in data; Redux passes data using props
Dispatch action
Actions describe changes with data payload
Action passed to Reducer
Reducer updates data store
Holds all data/state for the application
Globalized state
import { createStore } from 'redux' ;
const store = createStore ( rootReducer ) ;
Execute the action to the reducer
const dispatch = useDispatch ( ) ;
< Button title = "+" onPress = { ( ) => dispatch ( ( ) => plus ( 5 ) } > </ Button >
Describe what we want to do
export const plus = ( num ) => {
return {
type : 'INCREMENT' ,
payload : num
}
}
In this example, num is 5
Describe how actions transform state
Based on the action, we modify the store
const countReducer = ( state = 0 , action ) {
switch ( action . type ) {
case 'INCREMENT' :
return state + action . payload ;
case 'DECREMENT' :
return state - action . payload ;
}
}
state = 0 describes initial state
Extract data from Redux state using a selector function
// if using a rootReducer
const countReducer = useSelector ( state => state . count ) ;
In this example, we accessed the state (root reducer) and retrieved the count reducer from it where count: countReducer