How to connect Redux to a grandchild component
A significant number of developers incorporate Redux within their React applications because of the ease it provides in terms of handling complex data flows, which is to keep track of a large number of state variables.
With Redux, the state becomes a whole lot more manageable. This is primarily due to the globalization of the state in Redux, which enables us to access and update data comfortably.
Hierarchy of components
More often than not we find ourselves having the need to transfer data between components. When a component is enclosed within another component it is known as the child component and the enclosing component is the parent component. Subsequent children within the child component are referred to as grandchild components.
To pass information within such a structure, we can make use of Redux elements. Before that, let's quickly revise our Redux concepts.
Redux concepts
Actions | Objects that describe events or interactions in the application. |
Reducer | A method to update the state based on the actions we just talked about. It returns a new state. |
Connect | A method that connects a React component to the Redux store. This allows access to state and dispatching actions. |
Store | A central place to hold the application state and ensure the handling of state updates. |
Provider | A component that makes this store accessible to all components in the component tree. |
Note: The traditional way in React involves passing variables or information using props.
Passing information in Redux
Redux provides us with two highly useful keywords that we've just covered above, Store and connect. To aid in our purpose of passing information within the hierarchy, the connect method is used which binds the components to the Redux Store.
Note: The Redux Store keeps track of all the state tree of our application. This allows the components to access the state directly from the store.
Connecting Redux to the components
In order to understand the working of connect, a short snippet is given below:
const ConnectedComp = connect(mapStateToProps, mapDispatchToProps)(Comp);
This line demonstrates how a component can directly be connected to the Store without hierarchy interventions.
In easier words, when we connect a component to Redux using connect, it creates a new version of that component that is connected to the Store. It can then access the state and dispatch actions as needed.
Grandchild components
A sufficient example to illustrate the connection of React components down to the grandchild level will include a hierarchy of components and their direct connection to the Redux Store.
Let's take a scenario in which we type a word in our parent component and it is accessible from the grandchild component as well.