React Redux Component Lifecycle
Redux is a state management system. It gives you a place to save the state, a method to get the state, and a method to change the state in an application.
State is kept in store.
const store = createStore(reducer);
We can access that state using the method getState
const state = store.getState();
Finally we modify that state using actions and reducers. Actions are plain objects that describe what happened and show an intention to mutate state, which we never want to do directly.
{ type: 'ADD_TODO', text: 'Use Redux' }
A reducer is a function that receives the current state and an action object, decides how to update the state using the action type, and returns the new state
const initialState = { value: 0 }function counterReducer(state = initialState, action) {
// Check to see if the reducer cares about this action
if (action.type === 'counter/incremented') {
// If so, make a copy of `state`
return { ...state,
// and update the copy with the new value
value: state.value + 1 } }
// otherwise return the existing state unchanged
return state}
Each component in our app goes through the React Redux component lifecycle, like most lifecycles, goes through birth, growth, and death. Understanding these phases gives you the ability to manipulate and call functions at each of these phases.
The first phase is the mounting of the component to the DOM. The first method executed is constructor. It will set the initial state. Then we have render which will return our JSX code that will be converted into html later. Render is the only required function in the lifecycle. Now we will have access to componentDidMount(). This is a good place for fetch request to the backend or an API.
Next we have the updating phase. This will happen when either the state or props received change. After the change happens the render function will be triggered again. Then React will update the DOM and componentDidUpdate(prevProps, preState) will be called. This function has access to the previous props and state. In this function it is important to have a conditional statement if you are changing the props or state to prevent an infinite loop of updating the DOM from occurring.
The final phase is the unmounting phase. This is when the component is removed from the DOM and no longer shown. Here we have access to componentDidUnmount(). This is where you would perform any necessary cleanup, such as invalidating timers, canceling network requests, or cleaning up any DOM elements that were created in componentDidMount().