Redux vs Context API
I’ve seen a lot of my friends struggling to pass data between the components. Often they get confused about where to initialize a state. So today, I thought of sharing my views on this.
The simple and basic way to pass data/state from parent to child is through props. This is called prop drilling. Problems can arise when the child components are deeply nested. Prop drilling becomes so complex that the developer needs to appoint an assistant to find the right data XD.
So to solve this problem, normally people choose between REDUX and CONTEXT API. Confusion arises in the mind of beginners "When to use which one ? ".
First, let's take a second to understand what problem each of the two solves.
1. Context API
Mainly focuses on removing the problem of prop drilling. createContext() provides you with a Provider and a Consumer. Provider: a component that provides state/data to its children. Consumer: a component that uses the data/state from the provider.
Best tutorial I found on youtube
pros :
- a.Does not affect the bundle size as it is a build-in react tool.
- b. Excellent for managing static data.
- c. Easy learning curve.
- d. The setup required is minimal.
cons :
- a. Difficult to maintain complex applications.
- b. It is not designed for dynamic data.
- c. Debugging can be hard in nested components.
2. Redux
Redux,an open source library that is a predictable state container for js apps. You keep all your states in a centralized store and we cannot change its values as state is immutable. Global states are updated in reducer functions . tip : Use Redux devTools with redux for better experience.
Doc for redux : Best tutorial I found on youtube
pros :
- a. Specially designed for dynamic data.
- b. Easy to debug, enables tracking actions and data change
- c. Better code organization.
- d. Adds a layer, where you can decide how, when and if server response should be applied.
cons :
- a. Can affect the final bundle size.
- b. Difficult to learn and is often misleading for beginners.
WHEN TO USE WHICH ONE
If your primary aim is to avoid prop drilling, go for contextApi.If the application is
small-scale with more static data, choose context Api.If you are searching for a solution for everything ( state container, managing the application's logic outside components, centralizing your states or the data is refreshing frequently), go for Redux. Using redux-thunk for API calls along with redux is clean and easy to understand. Redux is easily extendable due to the ease of adding new data/actions after the initial setup . It also helps in keeping folders and files in our app in a structured way enhancing the readability. Use redux if you don’t want server response to change your data directly. Making it simple, choose redux if you are building a large-scale application.
I hope this gave some idea!