1. Name an alternative to the useState
Hook.
useReducer
2. Why might the useReducer
Hook
useReducer
might hook in cases where there is complex logic that requires multiple-sub values, or where one state relies on a previous one. useReducer
allows us to optimize performance, because we can pass DOWN logic instead of being forced to do callbacks.
Quote:
Main use cases are:
Writing more complex state update logic than just “overwrite the entire previous value”
Being able to more easily update multiple related fields in a single state update
Writing state update logic that can be tested outside the component, (because a reducer is just a function)
There are many good comments on when to use reducers vs. use states. Most of them agree that reducers are very helpful when dealing with many states that depend on each other.
The specific use case that comes up for me a lot is when your local state is a complex object or array of objects and you don’t want to have to overwrite the whole thing to make an update.
3. What are two ways to set the initial state?
init
function as the third argument, to initialize the state from outside of the reducer1. In terms of state, what does useReducer
expect to receive as a parameter?
a reducer
2. What does useReducer
return?
useReducer
returns an array that holds the current value of state, as well as a dispatch function
3. Explain dispatch
to a non-technical recruiter.
shape
of a thing in state. For example, we can make sure values are never duplicated or null
o// reducer template:
// reducer = (state, action) => new State;
const initialState = {
message: [],
user: [],
}
const addMessage = messageText =>
{
return {
type: 'ADD_MESSAGE',
payload: messageText,
}
}
function reducer(state, action)
{
if(action.type == 'ADD_MESSAGE'){
return{
// use the current values, as well as the ones from the payload
messages: [...state.messages, action.payload],
users: [...state.users],
}
else
{
// return the initial state, unchanged
return state;
}
}
// new state to return
return{
}
}
const updatedState = reducer(initialState, addMessage('Hello'));
console.log('the state we started with(still in state) and the processed state, using the reducer', initialState, updatedState);
useReducer Hook
action
is sort of like a request to a server, in that we attach the type
of request/action we want to run, as well as a body/payload
function App() {
const initialState = {
message: [],
user: [],
}
let [state, dispatch ] = useReducer(reducer, initialState);
return(
<ul>
{/* return list of items */}
</ul>
)
}