Refactor a Class Component with React hooks to a Function

InstructorKent C. Dodds

Share this video with your friends

Send Tweet

We have a render prop based <Query /> class component that allows us to make a GraphQL request with a given query string and variables and uses a GitHub graphql client that is in React context to make the request. Let's refactor this to a function component that uses the hooks useReducer, useContext, and useEffect.

ed leach
ed leach
~ 2 years ago

That's a lot of dependencies. They must be used in the class from which this refactoring comes.

FYI - I had to delete the package-lock.json file before npm install would work. Then everything worked.

Thanks.

ed leach
ed leach
~ 2 years ago

What class is this project from? Thanks.

Kent C. Dodds
Kent C. Dodds(instructor)
~ 2 years ago

I made this project for this course, but it's based on a workshop that my friend Matt Zabriskie and I gave several years ago.

Kent C. Dodds
Kent C. Dodds(instructor)
~ 2 years ago

Every lesson in the course has a link to GitHub. The lessons are sequential and the code follows that sequence in branches on the GitHub repo. So if you look at the code in the previous lesson, that's the code before the next lesson.

Tony Catalfo
Tony Catalfo
~ 2 years ago

let squaresCopy=squares.map(xOrO) setSquares(squaresCopy) console.log(squares,squaresCopy)

Why is the array squares one move behind squaresCopy?

Tony Catalfo
Tony Catalfo
~ 2 years ago

const [squares, setSquares]= useState(Array(9).fill(null)) let squaresCopy=squares.map(xOrO) setSquares(squaresCopy) console.log(squares,squaresCopy)

Why is the array squares one move behind squaresCopy?

Akhlesh Tiwari
Akhlesh Tiwari
~ 2 years ago

Thanks for awesome course. If I already have stable react class components, should I move on hooks?

Kent C. Dodds
Kent C. Dodds(instructor)
~ 2 years ago

I recommend having a real reason for refactoring existing and stable class components to hooks. I'd say you probably have better things to do with your time than refactor stable components for the fun of it.

If you need to make changes to a component though, then refactoring it to hooks first sounds great :)