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 ?
First, with Vite, we created a TypeScript React application. In this example, we will share across all React applications, the state user 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.tsxas below:
Import the
createContextfrom “react”;Define an
interfacefor the user that will be created and aninterfacefor 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 stateuserand a function to update this statehandleCreateUseralso 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
UserProviderwith 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
valueprop 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 and context.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.
Thank you for reading.
If you liked this article shared it!
I appreciate your feedback.





Top comments (0)