itswcl / react-count

using useReducer to make the count also useEffect to store localstorage

Repository from Github https://github.comitswcl/react-countRepository from Github https://github.comitswcl/react-count

react-count

useReducer

  • useReducer hook
  • counter function "+", "-" and "reset"
  • state declaration
    • const [state, dispatch] = useReducer(reducer, {count: 0})
  • reducer function
const reducer = (state, action) => {
    switch (action.type) {
        case XXXX:
            return XXX;
        default:
            return state
    }
}
  • run dispatch on click
() => dispatch({type: XXX})

useEffect

  • useEffect with local storage use
  • keep update local storage by state, only run if state.count updated
const key = 'test'
useEffect(() => {
    localStorage.setItem(KEY, state.count)
}, [state.count])
  • bring the element from local storage and update the state
useEffect(() => {
    // get the element out by localStorage.getItem
    const storedCount = localStorage.getItem(KEY);
    // update to integer because the store item is string
    state.count = Number(storedCount)
    // update the state of count by calling dispatch from useReducer
    dispatch({type: ACTION.STORED})
}, [])

About

using useReducer to make the count also useEffect to store localstorage


Languages

Language:JavaScript 50.0%Language:HTML 32.5%Language:CSS 17.5%