Skip to content

Handy React Snippets

  • Usereducer with logger

    unction enchanceDispatchWithLogger(dispatch) {
      return function (action) {
        console.groupCollapsed('Action Type:', action.type);
        return dispatch(action);
      }
    }
    
    function useReducerWithLogger(...args) {
      let prevState = useRef(initialState);
      const [state, dispatch] = useReducer(...args);
    
      const dispatchWithLogger = useMemo(() => {
        return enchanceDispatchWithLogger(dispatch);
      }, [dispatch]);
    
      useEffect(() => {
        if (state !== initialState) {
          console.log('Prev state: ', prevState.current);
          console.log('Next state: ', state);
          console.groupEnd();
        }
        prevState.current = state;
      }, [state]);
    
    
      return [state, dispatchWithLogger];
    }
    

    >/li>

Published inReact

Be First to Comment

Leave a Reply

Your email address will not be published. Required fields are marked *