React State Management (1) : context API
Tags: react, beginners
Published: 2022-03-07 05:48:21

This is a series of memos referring to the ways of React state management: context API, Redux, Redux toolkit and Recoil. The topic in this article is context API.

The chart below is the whole image of this practice application. ComponentA accepts user input text and passes it over to ComponentB as a prop. At the same time, context shares the input as the global state so that ComponentC and componentD can use it.

![The image of this application](https://cdn-images-1.medium.com/max/3416/1*i4GE9MZ7335A9htgbGtGew@2x.png)

This is the image of this application.

![](https://cdn-images-1.medium.com/max/2000/1*zUqew-PzV8gc-MPkiN-nHw.gif)

This is the structure of files in src folder.

![](https://cdn-images-1.medium.com/max/2000/1*VZaKncr_VAqSDSIRGsFtOw.png)

## 1) Create context 

### text-context.js
```javascript
    import React, { useState } from "react";
    export const TextContext = React.createContext({
      text: null,
      submit: (text) => {},
    });

    const TextContextProvider = ({ children }) => {
      const [text, setText] = useState(null);
      const submitHandler = (text) => {
        setText(text);
      };
      return (
        <TextContext.Provider
          value={{
            text,
            submit: submitHandler,
          }}
        >
          {children}
        </TextContext.Provider>
      );
    };
    export default TextContextProvider;
```
[**Context - React**](https://reactjs.org/docs/context.html)

## 2) Provide context

### index.js
```javascript
    import React from "react";
    import ReactDOM from "react-dom";
    import "./index.css";
    import App from "./App";
    import TextContextProvider from "./context/text-context";

    ReactDOM.render(
      <TextContextProvider>
        <App />
      </TextContextProvider>,
      document.getElementById("root")
    );
```
## 3) use context

### ComponentA
```javascript
    import { useState, useContext } from "react";
    import { TextContext } from "../context/text-context";
    import ComponentB from "./ComponentB";
    const ComponentA = () => {
      const [value, setValue] = useState("");
      const { submit } = useContext(TextContext);
      const changeHandler = (e) => {
        setValue(e.target.value);
        submit(e.target.value);
      };
      return (
        <>
          <input type="text" value={value} onChange={changeHandler} />
          <ComponentB text={value} />
        </>
      );
    };

    export default ComponentA;
```
### CompomentC
```javascript
    import { useContext } from "react";
    import { TextContext } from "../context/text-context";
    const ComponentC = () => {
      const { text } = useContext(TextContext);
      return (
        <>
          <h1>Uppercase</h1>
          <h2>{text && text.toUpperCase()}</h2>
        </>
      );
    };
    export default ComponentC;
```
### ComponentD
```javascript
    import { useContext } from "react";
    import { TextContext } from "../context/text-context";
    const ComponentD = () => {
      const { text } = useContext(TextContext);
      return (
        <>
          <h1>Lowercase</h1>
          <h2>{text && text.toLowerCase()}</h2>
        </>
      );
    };

    export default ComponentD;
```
The whole code is available [here](https://codesandbox.io/s/nostalgic-solomon-1l787i?file=/src/index.js)

Thank you for reading :)

The original article is [here](https://medium.com/@lada496/react-state-management-1-context-api-f792a3754162)