Rumors are flying! Could Context replace redux? Does it make prop drilling extinct? Even if Context !World peace, the React team has introduced a fantastic tool to simplify one of the most difficult problems frontend developers deal with daily: state management.

Over the past six months, there has been plenty of hype about the new Context. At the end of this post, you’ll know what it is, whether and when you should use it, and how to implement it in your applications.

What is Context?

Imagine React as a toolbox. In React 15, developers could only use prop drilling to manage their application’s state. (If you don’t know about prop drilling yet, go read this post. I’ll wait).

Developers started reaching for other toolboxes, like redux and MobX to help with more complicated state management. They offered alternative solutions to managing state, but they introduced complexity, increased the bundle size, and required learning another library in addition to React.

Like all abstractions, these tools came burdened with tradeoffs that felt worth it for large applications, but seemed like overkill for small and mid-sized applications.

When Should I Use Context?

I would recommend reaching for Context when you find yourself passing props down through three or more levels in your component tree. You might notice that you have renamed your props, making it challenging to determine the data’s origin. You might consider implementing context if a bunch of your components know about irrelevant data.

Do not hesitate to still use the other tools you have available, like prop drilling and redux. While Context can make it easier to pass props around in certain scenarios, it doesn’t give you access to some of the benefits redux offers, and it’s a more complicated abstraction than prop drilling.

#reactjs #api

How To Use the New React Context API
1.15 GEEK