Here is a CodeSandbox that has the example code below, and the linter highlights some of the issues: https://codesandbox.io/s/react-repl-bw2h1
Below is a basic example of what I'm trying to do. In a container component, I have a context AppContext
that is providing state to child components, <ChildConsumer />
and <ChildDispatcher />
.
The <ChildConsumer />
component is receiving this state using useContext
, and this seems to be working as expected.
Inside <ChildDispatcher />
, I'm trying to dispatch an action when a button is clicked. To do this, I've created a reducer reducer
that handles an action. I've also set up useReducer here that takes in reducer
and the initial store
state.
When I click the button, nothing happens. What I'm expecting to happen is that the dispatch
receives both the state
pulled off of useReducer
as well as an action
object, and passes these to the reducer. The reducer should see that the action of type BUTTON_CLICKED
was received, and should return a new state containing the old state as well as an additional 'goodbye'
item. Then, the child component <ChildConsumer />
should rerender with this new state.
import React, { createContext, useContext, useReducer } from "react";
import ReactDOM from "react-dom";
const store = [""];
const AppContext = createContext(store);
const ChildDispatcher = () => {
const reducer = (state, action) => {
switch (action.type) {
case "BUTTON_CLICKED":
return [...state, "goodbye"];
default:
return state;
}
};
const [state, dispatch] = useReducer(reducer, store);
const handleClick = () =>
dispatch(state, {
type: "BUTTON_CLICKED"
});
return <button onClick={handleClick}>press me</button>;
};
const ChildConsumer = () => {
const [consumer] = useContext(AppContext);
return <div>{consumer}</div>;
};
const App = () => {
return (
<div>
<h1>Using Context and useReducer</h1>
<AppContext.Provider value={["hello"]}>
<ChildConsumer />
<ChildDispatcher />
</AppContext.Provider>
</div>
);
};
const rootElement = document.getElementById("root");
ReactDOM.render(<App />, rootElement);