From the course: React Hooks

Unlock the full course today

Join today to access over 22,600 courses taught by industry experts or purchase this course individually.

Refactoring useState to useReducer

Refactoring useState to useReducer - React.js Tutorial

From the course: React Hooks

Start my 1-month free trial

Refactoring useState to useReducer

- [Instructor] Earlier in the course, we created a checkbox, and we handled the checked state by using useState. So every time I click on this checkbox, we call the setChecked function, and then we look at whatever the value of checked is, and we return the opposite. We can refactor this a little bit using useReducer, which may help with potential bugs that could pop up just by kind of working on a team with other people. So if we build all the functionality into useReducer, we can minimize the amount that can go wrong. Instead of importing useState, let's import useReducer, and we'll replace it here. Now, the second thing I want to do is I want to call this function toggle, and then inside of the useReducer function, again, it takes in two things. It's going to take in that function that's going to change the state. So literally, I want to just pull this nice little function here. This is going to be my reducer. So…

Contents