Context API : Share state across components easily
In this post I will show you how React Context API is great to pass data that can be used in any component in your application.
What is Context API ?
In React, data is passed from a parent to its child components as props. This can get tricky and complicated as your application grows and becomes more complex.
React context API allows you to share data to any component, by storing it in a central place and allowing access to any component that requests it.
Context is an API that is built into React, starting from React version 16.
How to use React Context API ?
First, with Vite, we created a TypeScript React application. In this example, we will share across all React applications, the stateuser
and a function handleCreateUser
to create a new user when a new data is received from the form.
- Creating our context file userDataContext.tsx in the src folder
src/context/userDataContext.tsx
as below:
- Import the
createContext
from “react”; - Define an
interface
for the user that will be created and aninterface
for the context. - Create context
UserContext
. In TypeScript we have to type the elements that we will be exporting in this context, in this case, the stateuser
and a function to update this statehandleCreateUser
also is necessary to type the createContext method with the correspondent interface. - Next, create the Provider that will share the context elements with all application. Using the function
UserProvider
with one parameterchildren
(children will be any child components that we want to share this context) and return this children wrapped by<UserContext.Provider>
. - We pass the two context elements through an object in the Provider
value
prop just like thatvalue={{user, handleCreateUser}}
. In TypeScript we have to type these elements and also type the parameter element that the Provider is receiving, in this case, children as a JSX.Element. - Finally, export our Context and Provider.
- In the main.tsx , we import the Provider and wrap our
<App />
with it as the image below:
Now we have access to the context elements we created in our entire application!
- Let’s use our context in the form.tsx component. To use it we have to import the context and the useContext hook from ‘react’.
The useContext hook take the UserContext as parameter and it is assign to a variable, in our exampleconst context = useContext(UserContext)
. This variable now is a object with our context elements context.user
andcontext.handleCreateUser
. The destructuring assignment can be used too.
To create a new user we use the handleCreateUser
function from the context and pass it to the onSubmit event (as we define in context, this function receive one parameter newuser). This way we create a new user and at same time we have access to the user
created from any component in our application.
I hope this guide gave you a better understanding of how to use React context API.