Skip to content

Why Redux?

Hemant Saraf edited this page Oct 11, 2021 · 4 revisions

Three ways of passing state variables from parent to leaf nodes are

  • Through prop drilling (pass as props from parent to child and child and ..till leaf)
  • Creating Context in parent component and warping Consumer Component in a Provider
  • Using Redux

Situations where Context can not be suitable

Suppose we have an example where we create context obj in parent containing

  1. count (state variable)
  2. setCount (count setter fn)
  3. Another string str (lets suppose its userName which remains constant for a user throughout his sessions)

We have all these three things in a context obj and we have Two consumer Components a. Counter (which consumes only count and setCount) b.MyName (consumes only user name)
Now when we wrap these two consumer comp. in a <MyContext.Provider value={count, setCount, str}> tag, we notice that when count changes even the MyName component is re-rendered. (becoz its wrapped in the same MyContext.Provider) This is an unnecessary re-render and redux does the job of preventing such unnecessary re-renders.

Note: This however is a typical example, we could create two context with different names one containing count & setCount another containing userName and use two Provider and have Counter and MyName in different Providers but that is cumbersome the bottom line is that its better to use Context only where state changes are not frequent like: authentication, light/dark theme etc

Also note that React.Memo can prevent re-render only when prev. props and new props are same (i.e. re-render due to parent Component getting re-rendered and no change to child components ) but it can't prevent re-render due to Context.Provider value changes