React State Management (1) : context API

Lada496
2 min readMar 7, 2022

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

This is the image of this application.

This is the structure of files in src folder.

1) Create context

text-context.js

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;

2) Provide context

index.js

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

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

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

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

Thank you for reading :)

--

--