Context API in React – Complete Guide
The Context API in React gives us an extremely powerful and easy way to pass data around without worrying about our app’s state. When you are working with React, there are times when you need to pass data around within different components but also have access to this data outside of those components as well. The Context also allows us to use arrow functions, one of the most common patterns you will use when structuring your code – especially if you want to keep things nicely contained inside a function but still be able to work with it outside of the function itself. Today, we will cover everything you need to know about creating Contexts in React and how they can help you make your apps easier to work with!
What is React Context?
React Context API is a way to share data between components easily. It lets you pass data from one component to another, which can be helpful when you want to keep track of state or pass information from one component to another.
What is React context in functional programming?
Like in any other programming language, we can use this concept in functional programming by creating functions that can access their state anywhere in the application. This is called the “functional state”. For example, if we have a function that calculates the sum of two numbers and we give it as an argument, another function which allows us to access state variables (like the sum variable) then this function will be able to access these variables and calculate their sum without checking them every time when calling itself. The same goes for other components and even the whole app state if we want some global variable available everywhere in our code base (like time or user id).
What are the problems solved by React Context API?
You do prop drilling when there are multiple nested components in the app, and you need to pass information from one component to another.
Prop drilling is a feature of React that allows you to pass data into components as props. This is useful when passing information from outside the component but also incredibly powerful.
Prop drilling is a way of passing data into components via their props. This allows you to pass information from the parent to the child.
Suppose the Parent component has to pass some information to GrandChild 3, then it has to pass the props into Child 2 first, and from Child 2, it will pass again as props to GrandChild 3. This is a minor example, but it becomes tedious in much larger codebases with multiple components. Also, Child 2 is not using the props but just passing them. Here is where Context API comes to the rescue. It acts like a global state where all the components, wherever they are, can access information passed through it.
How to use the Context API?
To understand the working of Context API, Let’s make a Theme Toggle Button.
Create a Context.jsx
file and import useState createContext
, and initialize it:
import useState, createContext, useContext } from "react";
const ThemeContext = createContext()
Code language: JavaScript (javascript)
Next, create a ThemeProvider function which takes children as props. Inside the function, initialize a dark theme useState and initialize a toggleTheme
, a function which will switch the value. We will wrap the children with Context Provider and supply the state value:
const ThemeProvider = ({children}) => {
const [darkTheme, setDarkTheme] = useState(true);
const toggleTheme = () => {
setDarkTheme(prevDarkTheme => !prevDarkTheme)
}
return (
<ThemeContext.Provider value={{
darkTheme,toggleTheme
}}>
{children}
</ThemeContext.Provider>
)
}
Code language: JavaScript (javascript)
Then we need to use the useContext
hook to use the Context in the child. Hence we will use a custom hook and return the themeContext
. Export both useTheme
and ThemeProvider
:
const useTheme = () => useContext(ThemeContext);
export {useTheme, ThemeProvider}
Code language: JavaScript (javascript)
So now we have the useTheme
, a custom hook to get the values, and ThemeProvider
, to wrap around the components into which we’ll pass the values.
Here we’ll import and wrap it around the App component in the index.jsx file:
import {ThemeProvider} from './Context'
<ThemeProvider>
<App />
</ThemeProvider>
Create another file called ThemeView.jsx and write a functional component inside it.
import React from 'react';
export const ThemeView = () => {
return (
<>
<div class='theme' >Theme preview</div>
<button >Toggle Theme</button>
</>
)
}
Code language: JavaScript (javascript)
import this component in the App component.
import { ThemeView } from './ThemeView.jsx'
export default function App() {
return (
<main>
<ThemeView/>
</main>
)
}
Code language: JavaScript (javascript)
Import the Custom Hook and the values inside the ThemeView function. Pass the values to the elements.
const { darkTheme, toggleTheme } = useTheme()
const ThemeStyles = {
backgroundColor:darkTheme ? 'black': 'white',
color: darkTheme ? 'white': "black",
}
return (
<>
<div class='theme' style={ThemeStyles}>Theme preview</div>
<button onClick={toggleTheme}>Toggle Theme</button>
</>
)
Code language: JavaScript (javascript)
On the initial render, this is what you’ll see:
On clicking the Toggle Theme, this is what you’ll see:
Voila, you now know the basics of Context API.
When should you use Context API?
Context is a way to store data used throughout your application. It’s an object that connects different parts of your application, and it can be passed around from one component to another.
You can use Context in several ways:
- To pass data around between components as props.
- To share state between components.
- To pass information from one component to another.
Does it replace State Management Libraries?
For many React newbies, Redux provides a convenient method to transfer data around. This is because Redux comes with the React context.
However, if you are only passing state down your component tree and not modifying it, you do not need a global state management framework like Redux.
While combining React context with a hook like useReducer to develop a minimal state management library without a third-party library is easy, it is typically not advised for performance reasons.
Conclusion
React Context API is a new addition to React to help you create modern web applications. It provides a way to share data between components in your application, which is especially useful if you have a lot of small components that need to communicate with each other.
It’s yet to be used everywhere in the React ecosystem, but it’s slowly becoming more popular.
I hope this guide was helpful and you took some insightful takeaways.
Sharing is caring
Did you like what Husain Mohammed Bhagat wrote? Thank them for their work by sharing it on social media.
No comments so far
Curious about this topic? Continue your journey with these coding courses: