DEV Community

Cover image for Context API : Share state across components easily
Gabriel Penteado
Gabriel Penteado

Posted on • Originally published at gabripenteado.Medium

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 ?
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.tsx as below:

context

  1. Import the createContext from “react”;

  2. Define an interface for the user that will be created and an interface for the context.

  3. Create context UserContext. In TypeScript we have to type the elements that we will be exporting in this context, in this case, the state user and a function to update this state handleCreateUser also is necessary to type the createContext method with the correspondent interface.

  4. Next, create the Provider that will share the context elements with all application. Using the function UserProvider with one parameter children (children will be any child components that we want to share this context) and return this children wrapped by <UserContext.Provider>.

  5. We pass the two context elements through an object in the Provider value prop just like that value={{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.

  6. Finally, export our Context and Provider.


  • In the main.tsx , we import the Provider and wrap our <App /> with it as the image below:

provider

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’.

useContext

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.

contextobj

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.

onsubmit

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)