Skip to content

22. Testing the context api

Course: React - chapter 23

Lets test our application, and observe the renders.

import React, { createContext, useContext, useState } from 'react';
const CountContext = createContext();
function CountContextProvider({ children }) {
const [count, setCount] = useState(0);
return <CountContext.Provider value={{count, setCount}}>
{children}
</CountContext.Provider>
}
function Parent() {
return (
<CountContextProvider>
<Incrase />
<Decrease />
<Value />
</CountContextProvider>
);
}
function Decrease() {
const {count, setCount} = useContext(CountContext);
return <button onClick={() => setCount(count - 1)}>Decrease</button>;
}
function Incrase() {
const {count, setCount} = useContext(CountContext);
return <button onClick={() => setCount(count + 1)}>Increase</button>;
}
function Value() {
const {count} = useContext(CountContext);
return <p>Count: {count}</p>;
}
// App Component
const App = () => {
return <div>
<Parent />
</div>
};
export default App;

import React, { createContext, useContext, useState } from 'react';
const CountContext = createContext();
function CountContextProvider({ children }) {
const [count, setCount] = useState(0);
return <CountContext.Provider value={{count, setCount}}>
{children}
</CountContext.Provider>
}
function Parent() {
return (
<CountContextProvider>
<Incrase />
<Decrease />
<Value />
</CountContextProvider>
);
}
function Decrease() {
const {count, setCount} = useContext(CountContext);
return <button onClick={() => setCount(count - 1)}>Decrease</button>;
}
function Incrase() {
const {count, setCount} = useContext(CountContext);
return <button onClick={() => setCount(count + 1)}>Increase</button>;
}
function Value() {
const {count} = useContext(CountContext);
return <p>Count: {count}</p>;
}
// App Component
const App = () => {
return <div>
<Parent />
</div>
};
export default App;

The Context API primarily addresses the issue of prop drilling by allowing you to share state across your component tree without needing to pass props through every level.

It doesn’t optimise renders in your application, which becomes important if/when your application becomes bigger