A simplified React playground for practicing useReducer and useContext.
- Logic: Uses standard
useStatefor theme switching. - UI: Minimal centered layout with a toggle button.
- Theming: CSS variables driven by
.lightand.darkclasses on a wrapper div.
src/App.jsx: Contains the core logic and UI structure.src/index.css: Contains the base styles and theme variables.
- Refactor
useStateinApp.jsxto useuseReducer.
- Create a context in the main top-level component using
createContext(null). - Set the context using
<Context.Provider value={"stateValue"}>and pass it to the children. - From the children, access the context using
useContext(OurContext)and use the state value as needed.
- The
useReducer(reducerFunction, initialState)function accepts two arguments: the reducer function and the initial state. - The
reducerfunction accepts two arguments,stateandaction, where the action describes what is needed from the dispatcher that is calling this function. useReducerreturns an array[state, dispatch], wheredispatchcalls thereducerfunction when an action is dispatched.- The reducer function generally uses
switchstatements and returns the new state, and it should also have a default return. - Dispatch is called, for example, in
onClick={() => {dispatch({ type: "action" })}}and can be used from anywhere inside the application, making state usage easy, compact, effective, and clean.