Skip to content

#10: State Reducer (useReducer) #12

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Open
wants to merge 2 commits into
base: 09_1
Choose a base branch
from
Open
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
40 changes: 26 additions & 14 deletions showcase/src/patterns/index.js
Original file line number Diff line number Diff line change
@@ -1,4 +1,5 @@
import React, {
useReducer,
useState,
useEffect,
useCallback,
Expand Down Expand Up @@ -147,29 +148,40 @@ const INIT_STATE = {
const callFnsInSequence = (...fns) => (...args) =>
fns.forEach(fn => fn && fn(...args))

const useClapState = ({ initialState = INIT_STATE } = {}) => {
const initialStateRef = useRef(initialState)
const [clapState, setClapState] = useState(initialStateRef.current)
const { count, countTotal } = clapState
const clapReducer = (state, { type, payload }) => {
const { count, countTotal } = state

const handleClapClick = useCallback(
() => {
setClapState({
count: Math.min(count + 1, MAX_CLAP),
countTotal: count < MAX_CLAP ? countTotal + 1 : countTotal,
switch (type) {
case 'clap':
return {
count: count + 1,
countTotal: countTotal + 1,
isClicked: true
})
},
[count, countTotal]
)
}
case 'reset':
return payload
default:
return state
}
}

const useClapState = ({
initialState = INIT_STATE,
reducer = clapReducer
} = {}) => {
const initialStateRef = useRef(initialState)
const [clapState, dispatch] = useReducer(reducer, initialStateRef.current)
const { count } = clapState

const handleClapClick = () => dispatch({ type: 'clap' })

const resetRef = useRef(0)
// reset only if there's a change. It's possible to check changes to other state values e.g. countTotal & isClicked
const prevCount = usePrevious(count)
const reset = useCallback(
() => {
if (prevCount !== count) {
setClapState(initialStateRef.current)
dispatch({ type: 'reset', payload: initialStateRef.current })
++resetRef.current
}
},
Expand Down