DEV Community

Kaziu
Kaziu

Posted on

Getting understand "useReducer in React" from real life sample

πŸ’– For those who have learned about useReducer, but still can't get when you should use intuitively

πŸ’Ž I implemented toggle button by useState

const [showMenu, setShowMenu] = useState<boolean>(true)

// when I want to show/hide toggle button
setShowMenu(!showMenu)
Enter fullscreen mode Exit fullscreen mode

πŸ’Ž But I realised there is better way by useReducer

const [showMenu, toggleShowMenu] = useReducer((prev) => !prev, true)

// when I want to show/hide toggle button, that's all!
toggleShowMenu()
Enter fullscreen mode Exit fullscreen mode

If you had like this experience "real life example of useReducer", make a comment please 😎

Top comments (0)