Effective use of IDE tools for code formatting and cleanup
Test-driven development as a workflow for React components
Strategies for refactoring and organizing React components
Improving development flow with TypeScript and Jest
Benefits of using Prettier and other formatting tools
Modern software development often requires a range of tools and methodologies to maintain code quality and enhance productivity. When working with React, an integrated development environment (IDE) can significantly streamline the process. An IDE is not just a text editor; it's a powerful tool that can automate repetitive tasks, ensure consistent code style, and manage complex project structures.
One of the critical features of an IDE is its ability to format code automatically. Using tools like Prettier, developers can maintain a consistent code style across a project. Prettier can reformat code to adhere to specific style guides, such as converting single quotes to double quotes, which might differ from the default settings of your IDE. This consistency is crucial when working in teams or when a project undergoes frequent updates.
Another valuable feature is the ability to optimize imports. Over time, a project can accumulate unused imports, which clutter the codebase and may introduce errors. The IDE can automatically detect and remove these, keeping the code clean and efficient. This function is especially useful when refactoring, as it allows developers to stay focused on the task without breaking their workflow.
Test-driven development (TDD) is another methodology that can enhance a developer's workflow. Writing tests before implementing a feature ensures that the code meets the expected behavior from the start. With tools like Jest and React Testing Library, developers can create comprehensive tests that simulate user interactions and verify component functionality. These tests can be run continuously, providing immediate feedback on code changes.
Refactoring is a common practice in software development that involves restructuring existing code without altering its external behavior. React's component-based architecture lends itself well to this practice. By breaking down larger components into smaller, more manageable ones, developers can improve code readability and maintainability. The IDE can assist in this process by automating the extraction of components and ensuring that all references are updated correctly.
TypeScript is a powerful tool for ensuring code quality and reducing runtime errors. By providing static type checking, TypeScript can catch errors early in the development process. This is particularly beneficial in a React project where components often interact in complex ways. IDEs can leverage TypeScript to offer intelligent code completion and error detection, further enhancing the developer's productivity.
One of the challenges in React development is managing component state. Class components provide a straightforward way to handle state with lifecycle methods, but they can be verbose. Functional components with hooks offer a more concise syntax and can simplify state management. However, both approaches have their place, and the choice often depends on the specific requirements of the project.
Another aspect of development that IDEs can improve is testing. Running tests in a headless browser environment, such as with jsdom, allows developers to verify component behavior without relying on a graphical user interface. This can speed up the testing process and integrate seamlessly into a continuous integration pipeline.
Finally, the integration of tools like Prettier into the IDE provides a seamless development experience. By automatically formatting code on save or on demand, developers can focus on writing code rather than worrying about style inconsistencies. This integration also extends to other tools like ESLint, ensuring that the codebase adheres to best practices.
In summary, the combination of a robust IDE, test-driven development, and the use of tools like Prettier, Jest, and TypeScript can significantly enhance the React development experience. By automating repetitive tasks, providing immediate feedback, and maintaining code quality, developers can stay in the flow and produce high-quality software efficiently.
ReactJS is wildly popular and thus wildly supported. TypeScript is increasingly popular, and thus increasingly supported.
The two together? Not as much. Given that they both change quickly, it's hard to find accurate learning materials.
React+TypeScript, with JetBrains IDEs? That three-part combination is the topic of this series. We'll show a little about a lot. Meaning, the key steps to getting productive, in the IDE, for React projects using TypeScript. Along the way we'll show test-driven development and emphasize tips-and-tricks in the IDE.
This workshop has been presented at React Advanced 2021, check out the latest edition of this React Conference.
FAQ
The main idea of the workshop is to demonstrate test-first development with React components, focusing on writing and developing code with tests before implementing functionality, to ensure that components behave as expected.
TypeScript helps in React development by providing type safety, which can catch errors at compile time, improve the readability and maintainability of the code, and enhance the development experience by providing features like autocompletion and refactoring tools.
The workshop discussed using Jest as the test runner and React Testing Library for testing React components. These tools help simulate user events and assert component states and outputs, providing a robust environment for test-first development.
The parent component's role is to manage state that can affect multiple child components. It handles state logic and passes down necessary data and callbacks to child components as props, allowing for cleaner and more modular code architecture.
Refactoring helps improve React application code by making it cleaner, more efficient, and easier to understand. It involves restructuring existing code without changing its external behavior to enhance performance, maintainability, and scalability.
Test-first development is recommended because it allows developers to define expected behaviors and interfaces upfront, reduce bugs, and maintain a clear understanding of component functionality, which overall improves code quality and reliability.
Today's workshop focuses on test-driven development in React, covering topics such as running, building, and testing React apps, using Prettier for code formatting, refactoring and creating subcomponents, implementing state and event handling in components, and project management and IDE integration. The workshop emphasizes the benefits of test-driven development, the use of IDEs, and the integration with tools like Jest and React Testing Library. TypeScript is also highlighted as a valuable tool for type checking and improving code quality. Overall, the workshop provides a comprehensive guide to developing React components test-first and following best practices in software development.
1. Introduction to Test-Driven Development in React
Today's workshop is about developing React components test first. Writing a test before writing the code and continuing to develop the code and component. At the end, you can see the actual result in the browser. The tutorial provides a URL where you can follow along, with write-ups, code, and videos. Each step in the tutorial has a link to working code for that segment.
2. Setting Up a React Project
In this part, we will discuss the benefits of test-driven development and the use of IDEs in the development process. We will also cover the setup and cleanup process, testing, and debugging. The tutorial is up to date with the latest version of Create React App and focuses on writing React components. We will create a new project using WebStorm and NPX, ensuring we have the latest version of Create React App. TypeScript support will be included. The output of Create React App will install the necessary dependencies for our project. Let's dive in!
3. Running, Building, and Testing React Apps
In this part, we learn about running and configuring a React app using Create React App. We explore running the app using the terminal and the IDE, as well as the benefits of using the IDE's npm tool. We also discuss the build process and the generation of a production-ready build directory. Finally, we touch on the topic of testing and the use of Jest as the official test runner.
4. Running Tests and Project Cleanup
Jest is the official test runner, and the testing library used is called testing library. They ensure compatibility between versions of Jest, testing library, and React. Running tests can be done from the command line, NPM scripts, or the package.json file. The tutorial covers the setup of npm run scripts in the IDE and create React app. Next, we will clean up the project and explore TypeScript. Any questions or comments before we begin? We'll use the expression 'Fail Faster' to catch mistakes early and focus on code reformatting with Prettier. We'll also remove unnecessary files generated by Create React App.
5. Using Prettier for Code Formatting in WebStorm
In this part, we learn about cleaning up files and using IDE features for code formatting. We explore the use of Prettier as a code formatter and discuss the choice of package manager between Yarn and npm. We also address the placement of development dependencies in Create React App and the installation of Prettier for code formatting. The IDE provides options to configure Prettier and run it on code reformatting. The audience engages in a discussion about why Create React App puts development dependencies under runtime dependencies.
6. Code Reformatting, Cleanup, and Renaming
We reformat the code using Printier, make the top-level component simple, and add a heading. We optimize imports, delete unused files, and handle import warnings. We also rename the app to My App and update the file name based on the React convention.
7. Undoing Refactorings in IDEs
When renaming components or files, IDEs offer the ability to undo the changes made during the refactoring process. This allows you to easily revert back to the previous state, including changes made in test code. It's a convenient feature that ensures you can easily undo an entire unit of work and restore everything to its original state.
8. Introduction to Testing
Next up, we're going to do actual testing. The workshop emphasizes the importance of enjoying the development process and finding the most productive way to work. We'll demonstrate this through the perspective of testing.
9. Running Tests with Jest and IDE Integration
Jest is the test runner used in the world of React and has great integration with IDEs like Webstorm. We can run our tests under a user-friendly interface and focus on fine-grained components. By stubbing code and returning dummy data, we can minimize errors and concentrate on specific parts. Let's set up a pretty face for testing by running tests directly from the gutter or running everything in a file.
10. Test-Driven Development in React
Test-driven development in React can be slower due to the transpiler and TypeScript compiler cycles. However, the IDE provides a dedicated tool window for testing, allowing developers to stay focused on the code and receive immediate feedback on test results. By setting up a run configuration, developers can run all tests or individual tests, depending on their needs. The IDE's integration with Jest and the Node.js debugger further enhances the testing experience, providing features like code autocompletion, failure notifications, and the ability to run tests in the debugger. This approach to development, known as TDD, helps developers work deliberately and under control, without distractions.
11. Test-Driven Development Workflow
To practice test-driven development, the speaker hides the project tool, turns off tabs, and splits the windows. They have their code on the left, test on the right, and test output running at the bottom. The speaker demonstrates making a change in the code that breaks the tests, highlighting the benefit of having everything on one screen. They also mention receiving desktop notifications for test results.
12. Debugging and Parameterization of Components
In this part, the speaker pauses for questions and addresses the use of Enzyme and React Testing Library. They explain the switch from Enzyme to React Testing Library and the benefits of writing tests that mimic user behavior. The speaker also discusses the parameterization of the app component and the creation of a helper function called label. They demonstrate writing a test for the label function and explain the process of importing and running the test. The speaker emphasizes the ease of assessing JavaScript functions without React dependencies. The tutorial focuses on making the function more dynamic.
13. Parameterization and Test-Driven Development
We want to have it be parameterized so you can say hello, world, for example, or do something like capitalize the thing that was passed. Now we're going to do test driven development. We're going to change it to break. So I'm going to change this to react all upper.
14. Implementing Behavior and Debugging
To implement the behavior being tested, a parameter called 'name' is accepted and used in a template string. The IDE does not provide help for this, but TypeScript identifies the issue. By passing a value to the test, the failure is caught early. The IDE warns about missing type information, but can infer it automatically. The combination of TypeScript, test-first development, and the debugger allows for efficient debugging without the need for console.log statements. The tests can be stepped through and the problem can be identified and fixed. This approach allows developers to stay in the flow and work efficiently.
15. Using Chrome Dev Protocol and IDE Features
We discuss the use of the Chrome dev protocol to control Chrome's JavaScript engine and execute code remotely. This allows us to debug and test our code in a private Chrome window without affecting our personal Chrome usage. We also mention the use of jsdom in Node.js and inquire about potential replacements. Next, we explore features in TSX and ECMAScript 6, and how the IDE can assist with code completion. We clean up our code and ensure our test configuration is running properly.
16. Refactoring and Creating Subcomponents
Alexei suggests using Cypress for unit tests. The speaker discusses the benefits of test-driven development and the use of IDEs. They mention taking a break and the use of Postman for APIs. The speaker plans to start refactoring and creating subcomponents. They explain the process of test-driven development and demonstrate making a subcomponent. The test fails, but the speaker plans to import the component and continue the refactoring process.
17. Extracting Subcomponent and Refactoring
In this part, the speaker demonstrates test-driven development by extracting a subcomponent. They show how to trigger the extract component feature using the IDE's refactor menu. The speaker discusses violating the single responsibility principle and decides to move the subcomponent to its own file. They demonstrate the IDE's ability to automatically generate imports and clean up unnecessary symbols. The importance of unit tests focusing on a single unit and the benefits of test-driven development in refactoring are emphasized.
18. Refactoring and Default Prop Value
We extract the inline type information about the props to a standalone type called Heading Props. We reference this type in the code, making it easier to read. However, we still need to address the issue of the default prop value. By using an ES6 default argument, we can satisfy the old contract and ensure that the tests pass. TypeScript may raise an error due to the required name prop, but we can resolve this by informing TypeScript that the name prop is optional. This approach allows us to adhere to the single responsibility principle and maintain a clean code structure.
19. Refactoring and Extracting Components
We refactor and extract a component by moving the subcomponent and its dependencies to a new file. JSX and TSX have certain restrictions and error messages provided by TypeScript. The combination of test-first development and typing in TypeScript allows us to fail faster and receive immediate feedback in our IDE. We discuss various topics related to testing, such as mocking child components, code coverage, and the use of the React Testing Library. Storybook is also mentioned as a tool for showcasing component variations. We then switch to class components and introduce the concept of props. We create a new file for a counter component and write a test for it.
20. Wiring Counter Component and Testing
We resolved the import for the counter component and added tests for the label and count. We extracted the type information for the props to a standalone type and added a default value for the label prop. We then wired the counter component into the app and wrote tests to ensure it was rendering correctly. Everything passed, and we are ready to move on.
21. Implementing State in Counter Component
My tests passed, proving that my counter class component is in the parent app component. Let's take a look at it in the browser. The counter component is styled poorly, but we'll address that in the next part. We have one hour left, so let's stop for questions. We discuss testing child components and the use of selectors. There's also mention of visual testing and the use of Cypress. We switch from a functional component to a class-based component to have easy local state. We start with a failing test and implement the counter component. The test fails because the counter does not start at zero. We proceed to implement the state in the class component.
22. Managing Component State with TypeScript
I learned class-based components first and there's a place for local state. We added a second generic for the state alongside the prompts and put in some initial state as a class variable. However, immutability is a problem and we should use the set state method. We can use TypeScript to detect read-only assignments. We set a module scope value for the initial state and use the read-only prefix. We can now change the value of the state. Let's get back to having a starting value and implement it using a lifecycle method. If a prop was passed in, we call setState instead of manual assignment.
23. Handling Clicks to Increment Counter
We fixed the issue with the test not running the componentMount lifecycle. Now we need to wire the counter component into the UI. We have a counter component that can be passed props and state, is configurable from the outside, and keeps track of counts. We discuss the importance of being specific in a component's contract. We move on to the next part, where we will handle clicks to increment the counter and simulate clicks in testing.
24. Implementing Event Handling in Counter Component
I wanted to simulate clicking on an element to go from 0 to 1. The test failed because the event handler was not implemented. We need an on-click handler in the counter component. We wrote failing tests and implemented the on-click handler using an arrow function. However, this approach is discouraged due to frequent recompilation. We moved the arrow function to a class method for better test isolation. The onClick handler was modeled correctly with the event passed in. The tests passed, demonstrating the benefits of doing it the right way.
25. Refactoring and Handling Shift Click Test
We set the type explicitly to eliminate the squiggle. We realized the order of the ternary was wrong and corrected it. TypeScript helped us along the way by providing autocomplete and type information. The tests passed, and we now have a shift clickable counter. We need to handle the test for shift click. We discuss the use of user event and fire event in testing library. We decide to use fire event as the better option. We run the import manually and focus on the task at hand.
26. Testing Increment Counter and Simulating Event
We clone the last test and simulate holding the Shift key while clicking on the count to increase it by 10. We switch from FireEvent to UserEvent for richer interaction. The test passes because the implementation is already in the event handler. We discuss the option of testing increment counter via render or by calling the function and checking the state. The latter option resembles normal JavaScript testing and provides faster and more reasonable failures.
27. Refactoring Counter Component and Testing
In this step, we refactor the counter component to remove its state and logic about event handling. The parent component will handle these responsibilities and pass them as props to the counter. We also discuss the testing strategy and modeling in TypeScript. The tests are modified to accommodate the changes, and TypeScript issues are resolved. We are now ready to proceed with the final step.
28. Handling Clicks to Increment Counter
We fixed the issue with the test not running the componentMount lifecycle. Now we need to wire the counter component into the UI. We have a counter component that can be passed props and state, is configurable from the outside, and keeps track of counts. We discuss the importance of being specific in a component's contract. We move on to the next part, where we will handle clicks to increment the counter and simulate clicks in testing.
29. Project Management and IDE Integration
They do a great job running the project and keeping the roadmap up to date. They're into type theory now and trying to move huge parts. TypeScript is mentioned as well. The licenses for WebSR and IntelliJ are separate, but there's an all products pack for access to all IDs. The calmness and discipline of staying in the IDE during development are appreciated. Dylan's comment is acknowledged, and the speaker expresses interest in learning from them. June's point is mentioned, but the speaker is unsure of its significance.
Ivan’s first attempts at performance debugging were chaotic. He would see a slow interaction, try a random optimization, see that it didn't help, and keep trying other optimizations until he found the right one (or gave up). Back then, Ivan didn’t know how to use performance devtools well. He would do a recording in Chrome DevTools or React Profiler, poke around it, try clicking random things, and then close it in frustration a few minutes later. Now, Ivan knows exactly where and what to look for. And in this workshop, Ivan will teach you that too. Here’s how this is going to work. We’ll take a slow app → debug it (using tools like Chrome DevTools, React Profiler, and why-did-you-render) → pinpoint the bottleneck → and then repeat, several times more. We won’t talk about the solutions (in 90% of the cases, it’s just the ol’ regular useMemo() or memo()). But we’ll talk about everything that comes before – and learn how to analyze any React performance problem, step by step. (Note: This workshop is best suited for engineers who are already familiar with how useMemo() and memo() work – but want to get better at using the performance tools around React. Also, we’ll be covering interaction performance, not load speed, so you won’t hear a word about Lighthouse 🤐)
With the release of React 18 we finally get the long awaited concurrent rendering. But how is that going to affect your application? What are the benefits of concurrent rendering in React? What do you need to do to switch to concurrent rendering when you upgrade to React 18? And what if you don’t want or can’t use concurrent rendering yet?
There are some behavior changes you need to be aware of! In this workshop we will cover all of those subjects and more.
Join me with your laptop in this interactive workshop. You will see how easy it is to switch to concurrent rendering in your React application. You will learn all about concurrent rendering, SuspenseList, the startTransition API and more.
The addition of the hooks API to React was quite a major change. Before hooks most components had to be class based. Now, with hooks, these are often much simpler functional components. Hooks can be really simple to use. Almost deceptively simple. Because there are still plenty of ways you can mess up with hooks. And it often turns out there are many ways where you can improve your components a better understanding of how each React hook can be used.You will learn all about the pros and cons of the various hooks. You will learn when to use useState() versus useReducer(). We will look at using useContext() efficiently. You will see when to use useLayoutEffect() and when useEffect() is better.
TypeScript is not just types and interfaces. Join this workshop to master more advanced features of TypeScript that will make your code bullet-proof. We will cover conditional types and infer notation, template strings and how to map over union types and object/array properties. Each topic will be demonstrated on a sample application that was written with basic types or no types at all and we will together improve the code so you get more familiar with each feature and can bring this new knowledge directly into your projects. You will learn:- - What are conditional types and infer notation- What are template strings- How to map over union types and object/array properties.
In this workshop, you'll learn how to build your first full stack dapp on the Ethereum blockchain, reading and writing data to the network, and connecting a front end application to the contract you've deployed. By the end of the workshop, you'll understand how to set up a full stack development environment, run a local node, and interact with any smart contract using React, HardHat, and Ethers.js.
TypeScript has a powerful type system with all sorts of fancy features for representing wild and wacky JavaScript states. But the syntax to do so isn't always straightforward, and the error messages aren't always precise in telling you what's wrong. Let's dive into how many of TypeScript's more powerful features really work, what kinds of real-world problems they solve, and how to wrestle the type system into submission so you can write truly excellent TypeScript code.
This transcription provides a brief guide to React rendering behavior. It explains the process of rendering, comparing new and old elements, and the importance of pure rendering without side effects. It also covers topics such as batching and double rendering, optimizing rendering and using context and Redux in React. Overall, it offers valuable insights for developers looking to understand and optimize React rendering.
Remix is a web framework built on React Router that focuses on web fundamentals, accessibility, performance, and flexibility. It delivers real HTML and SEO benefits, and allows for automatic updating of meta tags and styles. It provides features like login functionality, session management, and error handling. Remix is a server-rendered framework that can enhance sites with JavaScript but doesn't require it for basic functionality. It aims to create quality HTML-driven documents and is flexible for use with different web technologies and stacks.
Kent C. Dodds discusses the concept of problem elimination rather than just problem-solving. He introduces the idea of a problem tree and the importance of avoiding creating solutions prematurely. Kent uses examples like Tesla's electric engine and Remix framework to illustrate the benefits of problem elimination. He emphasizes the value of trade-offs and taking the easier path, as well as the need to constantly re-evaluate and change approaches to eliminate problems.
The Talk discusses React Forget, a compiler built at Meta that aims to optimize client-side React development. It explores the use of memoization to improve performance and the vision of Forget to automatically determine dependencies at build time. Forget is named with an F-word pun and has the potential to optimize server builds and enable dead code elimination. The team plans to make Forget open-source and is focused on ensuring its quality before release.
Today's Talk explores the use of the useEffect hook in React development, covering topics such as fetching data, handling race conditions and cleanup, and optimizing performance. It also discusses the correct use of useEffect in React 18, the distinction between Activity Effects and Action Effects, and the potential misuse of useEffect. The Talk highlights the benefits of using useQuery or SWR for data fetching, the problems with using useEffect for initializing global singletons, and the use of state machines for handling effects. The speaker also recommends exploring the beta React docs and using tools like the stately.ai editor for visualizing state machines.
This Talk discusses modern web debugging and the latest updates in Chrome DevTools. It highlights new features that help pinpoint issues quicker, improved file visibility and source mapping, and ignoring and configuring files. The Breakpoints panel in DevTools has been redesigned for easier access and management. The Talk also covers the challenges of debugging with source maps and the efforts to standardize the source map format. Lastly, it provides tips for improving productivity with DevTools and emphasizes the importance of reporting bugs and using source maps for debugging production code.
Comments