Project Overview
In this project, we'll refactor class components in a React application into function components using React Hooks. This transformation is a common task for React developers as the community has embraced hooks as the standard way to handle state and side effects in React components.
By the end of this tutorial, you'll understand how to:
- Use the
useStateHook to convert state instance variables to function-based state variables - Understand React lifecycle methods (
componentDidMount,componentDidUpdate,componentWillUnmount) and their function component equivalents - Use
useEffectto replicate the behavior of those lifecycle methods - Use
useRefto create a ref that persists across renders - Test your refactored components with React Testing Library
Project Setup
Before diving into the refactoring process, make sure you have:
- Cloned the Widgets application starter
- Run
npm installto install all dependencies - Started the application with
npm run devto see the widgets displayed at http://localhost:5173
Testing
The project comes with test coverage using React Testing Library on a Jest framework. These tests will help ensure your refactoring doesn't break existing functionality.
Run npm test to start tests in watch mode. The tests will automatically run whenever you change a file.
- Press
ato run all tests - Press
pto filter by a filename pattern
It's recommended to keep tests running in watch mode as you refactor to catch issues immediately.
Tutorial Structure
This tutorial is divided into five phases, each focusing on a specific component:
- Phase 1: App Component - Introducing
useStatefor basic state management - Phase 2: Folder Component - Working with props and component interaction
- Phase 3: Weather Component - Using
useEffectfor API calls and data fetching - Phase 4: Clock Component - Working with intervals and cleanup
- Phase 5: Autocomplete Component - Advanced state, refs, and component updates
Each phase builds on the concepts from the previous ones, gradually introducing more complex uses of React Hooks.