useReducer
https://frontendmasters.com/courses/intermediate-react-v2/usereducer/
useReducer
A compenent that can redefine the color of an element. This is a simple Redux implementation.
With our current knowledge, this would be a lot of state and lot of use..
to keep track of, as there are three different color channels to keep track of.
What is a reducer
A reducer function is one that takes a state, some actions and return a new state.
// **** Reducer.js ****
import React, { useReducer } from "react";
// fancy logic to make sure the number is between 0 and 255
const limitRGB = num => (num < 0 ? 0 : num > 255 ? 255 : num);
const step = 50;
// **** 3. the reducer functions. ↴
const reducer = (state, action) => {
// very Redux like architecture
// ...easy to test
switch (action.type) {
case "INCREMENT_R":
return Object.assign({}, state, { r: limitRGB(state.r + step) });
case "DECREMENT_R":
return Object.assign({}, state, { r: limitRGB(state.r - step) });
case "INCREMENT_G":
return Object.assign({}, state, { g: limitRGB(state.g + step) });
case "DECREMENT_G":
return Object.assign({}, state, { g: limitRGB(state.g - step) });
case "INCREMENT_B":
return Object.assign({}, state, { b: limitRGB(state.b + step) });
case "DECREMENT_B":
return Object.assign({}, state, { b: limitRGB(state.b - step) });
default:
return state;
}
};
const ReducerComponent = () => {
// **** 1. setting up the reducer. ↴
// useReducer receives the reducer function, and an initial state.
// the difference from Redux is that you don't have to run it
// on the first time.
const [{ r, g, b }, dispatch] = useReducer(reducer, { r: 0, g: 0, b: 0 });
// the left hand side tuple values above:
// just the color definition object
// and the dispatch function
// that let's you dispatch an action to the reducer
return (
<div>
<h1 style={{ color: `rgb(${r}, ${g}, ${b})` }}>useReducer Example</h1>
<div>
<span>r</span>
// **** 2. the available dispatch functions. ↴
<button onClick={() => dispatch({ type: "INCREMENT_R" })}>➕</button>
<button onClick={() => dispatch({ type: "DECREMENT_R" })}>➖</button>
</div>
<div>
<span>g</span>
<button onClick={() => dispatch({ type: "INCREMENT_G" })}>➕</button>
<button onClick={() => dispatch({ type: "DECREMENT_G" })}>➖</button>
</div>
<div>
<span>b</span>
<button onClick={() => dispatch({ type: "INCREMENT_B" })}>➕</button>
<button onClick={() => dispatch({ type: "DECREMENT_B" })}>➖</button>
</div>
</div>
);
};
export default ReducerComponent;
Doing this for your whole applicaton
You use useReducer
and Context together and it's same thing! :)
Brian doesnt use Redux much anymore because of this.