What is React context API?
Aneh Thakur
. 3 min read
React Context is a way to share values that are considered “global” for a tree of React components, such as the current authenticated user, theme, or preferred language. It allows you to avoid prop drilling, or the passing of props through multiple levels of the component tree just to get them to a deeply nested component that needs them.
Instead of passing a prop through several levels of the component tree manually, you can create a context using React.createContext
, and then provide a value for the context using a Context.Provider
component. Any component in the tree that needs access to the context value can then use a Context.Consumer
component or the useContext
hook to consume the context value.
Here’s an example of how you might use the Context API to provide a theme to a deeply nested component:
// Create the context const ThemeContext = React.createContext('light'); function App() { return ( // Provide a value for the context <ThemeContext.Provider value="dark"> <Nav /> </ThemeContext.Provider> ); } function Nav() { return ( // Consume the context value <ThemeContext.Consumer> {theme => ( <div className={`nav-${theme}`}> <Link /> </div> )} </ThemeContext.Consumer> ); } function Link() { // Consume the context value using the useContext hook const theme = useContext(ThemeContext); return <a className={`link-${theme}`}>Home</a>; }
In this example, the Link
a component is able to access the theme
value from the ThemeContext
without having to pass the value down through multiple levels of the component tree.
It’s important to note that the Context API is primarily intended for sharing values that are considered “global” for a tree of components, rather than for passing props between components that are not deeply nested. If you only need to pass a prop through a few levels of the component tree, it’s generally recommended to use traditional prop passing instead.
What is prop drilling?
Prop drilling, also known as “prop tunneling,” refers to the practice of passing props down through multiple levels of the component tree in order to get them to a deeply nested component that needs them.
For example, consider the following component tree:
App Page Header Nav Link
If the Link
component needs access to a prop that is passed to the App
component, it would typically have to be passed down through every component in the tree:
function App(props) { return <Page {...props} />; } function Page(props) { return <Header {...props} />; } function Header(props) { return <Nav {...props} />; } function Nav(props) { return <Link {...props} />; } function Link(props) { // Now the Link component has access to the prop }
This can become cumbersome and difficult to manage, especially if you have a large component tree and need to pass several props through multiple levels.
The Context API is one way to avoid prop drilling by allowing you to share values that are considered “global” for a tree of components, rather than passing them down through the tree manually.
Difference between context API and Redux?
The Context API and Redux are both ways to manage state in a React application, but they work in different ways and are intended for different use cases.
The Context API is a way to share values that are considered “global” for a tree of React components, such as the current authenticated user, theme, or preferred language. It allows you to avoid prop drilling, or the passing of props through multiple levels of the component tree just to get them to a deeply nested component that needs them. The Context API is primarily intended for sharing values that are considered “global” for a tree of components, rather than for passing props between components that are not deeply nested.
On the other hand, Redux is a state management library that allows you to manage the state of your application in a centralized store. It uses a unidirectional data flow and follows the principles of functional programming to make it easier to reason about your application’s state.
Redux is often used in larger applications with complex states, where the state is updated by multiple components and needs to be persisted across the application. It is also useful for applications that need to be able to undo and redo actions, as it provides a clear history of the state changes that have occurred.
In general, the Context API is better suited for sharing values that are considered “global” for a tree of components, while Redux is better suited for managing complex states in larger applications.
More Stories from
Get Started with TypeScript: A Beginner's Guide with Code Samples
TypeScript is a popular, powerful programming language that is a superset of JavaScript. If you're new to TypeScript, this beginner's guide is the perfect place to start. With clear explanations and code samples, you'll learn the basics of TypeScript and
TypeScript vs TSX: Understanding the Differences
This article delves into the key differences between TypeScript and TSX, two programming languages used for developing complex web applications. From syntax and static typing to React integration and code organization, learn which language is best suited
Learn about the different types of React hooks with code examples
React hooks are a powerful feature that allow you to use state and other React features inside functional components. In this tutorial, you will learn about the different types of hooks available in React, and see code examples of how to use them in your
A step-by-step guide to deploying a ReactJS app online
Learn how to deploy your ReactJS app to the internet with this comprehensive tutorial. From setting up a hosting platform to building and uploading your code, we'll cover all the steps you need to take to get your app live. Whether you're a beginner or an
All about MongoDB
MongoDB is an open-source document-oriented database that is designed to store a large scale of data and also allows you to work with that data very efficiently. It is categorized under the NoSQL (Not only SQL) database because the storage and retrieval o