From the course: React Hooks
Unlock the full course today
Join today to access over 24,400 courses taught by industry experts.
Solution: Building a counter - React.js Tutorial
From the course: React Hooks
Solution: Building a counter
(dramatic music) - [Instructor] We have our actions here, increment and decrement, and now we need to make use of them within a reducer function. So a reducer function takes in a state and an action, like increment or decrement, and it returns a new state. So what I need to do here is define these different cases for each of those actions. So if the actions.increment happens, then we want to return a new state where we push in the old state and increment the count. So state account plus one, and I want to make sure to set the count to state.count there. We do it again slightly differently. When we decrement this time, we return... state count is state.count minus one. All right, so from here, we need these changes to be reflected inside of the component. So we'll use our useReducer hook. That will look like this. We create an array here for dispatch and state, and then useReducer takes in two things. So it takes in the function and it takes in the initializer, so the initial state…
Contents
-
-
-
-
-
-
(Locked)
Handling complex state with useReducer2m 20s
-
(Locked)
Refactoring useState to useReducer1m 39s
-
Dispatching actions with useReducer4m 33s
-
(Locked)
Managing form inputs with useRef4m 58s
-
(Locked)
Creating controlled components with useState2m 50s
-
(Locked)
Solution: Building a counter3m 23s
-
(Locked)
-
-
-