This weekly report mainly summarizes the content from various places.
Technology#
React Best Practices in 2023 - Part 4: Writing Clean and Efficient React Code- Best Practices and Optimization Techniques#
This article discusses various best practices for writing clean and efficient code in React applications. It recommends implementing error boundaries, using React.memo for functional components, employing code checking tools to improve code quality, avoiding default exports, using object destructuring, utilizing Fragments, and passing objects instead of multiple props. These practices can enhance the maintainability, performance, and readability of the codebase.
- When writing React code, implementing methods such as error boundaries, using React.memo, and object destructuring can lead to clean and efficient code.
- Using code checking tools like ESLint can improve code quality and consistency.
- Prefer named exports over default exports, use Fragments instead of unnecessary wrapping divs, and lean towards passing objects rather than multiple props to make the codebase more organized and navigable.
Avoid parameter drilling by using the Node.js AsyncLocalStorage#
This article discusses the challenges of sharing context in Node.js applications and introduces the AsyncLocalStorage class, which provides a way to store specific context data during the lifecycle of a web request or any other asynchronous operation. It is not recommended to use global variables to share context, and passing parameters or attaching them to request objects can be cumbersome. The AsyncLocalStorage API can be used to associate IDs, store the current user, transaction IDs, report data, etc. The article also mentions the Async Context proposal in JavaScript.
- When dealing with asynchronous code, global variables can cause issues as they may interfere with each other.
- The AsyncLocalStorage class in Node.js provides a way to store specific context data throughout the lifecycle of asynchronous operations, avoiding interference.
- The Async Context proposal in JavaScript aims to extend the use of AsyncLocalStorage and may become part of the ECMAScript standard in the future.
First Experience and Practice with React Server Component - Migrating Blog to Next.js App Router#
- Migrated from Hexo to Next.js, utilizing React Server Component and Next.js 13's App Router.
- Retained Hexo as a CMS but required writing many additional serialization steps.
- In React Server Component, Hexo's API can be called directly, and the Document and Query instances returned by Hexo API can be passed around as props.
- Implemented Nested Layout using Next.js App Router.
- Introduced the ability to ensure priority updates of high user experience stat data by leveraging React 18's Concurrent Rendering capabilities.
Things you might not know about Next Image#
This article explains how the Next.js Image component works and clarifies some misunderstandings surrounding it. The Next Image component is an image optimization solution that requires no cumbersome operations, supports modern formats, and generates multiple versions for different screen sizes. The architecture of Next Image includes three components: the React Next Image component, the Image API, and the Image Optimizer. The Image API acts as an image proxy, while the Image Optimizer uses different libraries based on the environment. The article debunks misconceptions about image cropping, clarifies the difference between displayed image width and loaded image width, and explains how to use image optimization without the Next Image component. It also discusses the importance of using import to bring in local images and understanding the 'sizes' attribute for responsive images.
- The Next Image component in Next.js provides image optimization features without cumbersome operations, supporting modern formats and generating custom versions for different screen sizes.
- The component does not actually crop images but uses width and height attributes to prevent layout shifts and stretches or shrinks images when mismatches occur.
- The Image API can be used independently with the Next Image component for scenarios like rendering images on a canvas or optimizing OG images.
Faking a selector with Scroll-Driven Animations#
This article discusses how to use scroll-driven animations to simulate a selector that matches elements captured by a scroll container with scroll snapping enabled. The article provides code and implementation methods, along with a demonstration. However, the method is not perfect and has some limitations. The author suggests that a style setting method suitable for capturing elements should be built into CSS.
- Scroll-driven animations can be used to simulate a fictional selector, enabling dynamic element styling based on scroll snapping.
- By combining scroll-driven animations with other CSS features, developers can create unique effects such as sticky positioning, text shrinking, and scroll retention states.
- Although the provided code offers a workaround for applying styles to captured elements, it has limitations and is seen as a clever solution, highlighting the need for a dedicated CSS feature to handle captured elements.
Midjourney From Scratch to Practical Application#
Building a full-stack, fully type-safe pnpm monorepo with NestJS, NextJS & tRPC#
This tutorial guides you in building a full-stack, end-to-end type-safe pnpm monorepo using NestJS, NextJS 13, and tRPC. It covers setting up the monorepo, adding NestJS applications, adding NextJS 13 applications, and making configuration updates for seamless integration between the two applications. The tutorial also demonstrates how to use tRPC in NestJS and NextJS, including adding a tRPC server to NestJS and a tRPC client to NextJS. Finally, it provides instructions for deploying the monorepo to Railway. This tutorial emphasizes the advantages of the development experience and the chosen tech stack.
- This tutorial guides you in building a full-stack, end-to-end monorepo using NestJS, NextJS 13, and tRPC, providing a seamless development experience.
- The monorepo setup uses pnpm workspaces, allowing independent management of frontend and backend projects within the same repository.
- The tRPC server is integrated into NestJS, providing type-safe communication between backend and frontend applications.
Thinking in React Query#
An Introduction to Streaming on the Web#
Web streams provide a standardized way to asynchronously send and receive data over network connections. They enhance the performance and responsiveness of web applications through real-time updates and interactivity. Web streams can be categorized into three types: WritableStream, ReadableStream, and TransformStream. The basic unit of data in a stream is a chunk, which can vary in size and shape. Common methods for interacting with web streams include the Fetch API and the getReader method. Web streams also have the capability to handle backpressure, ensuring a balance between data production and consumption. Server-Sent Events (SSE) is another method for streaming real-time updates from the server to the client.
- Web streams provide a standardized and efficient way to handle data, enabling real-time updates and interactivity in web applications.
- Backpressure handling in web streams ensures a balance between data production and consumption, preventing memory overflow and maintaining a smooth data flow.
- Server-Sent Events (SSE) use long-lived HTTP connections to stream updates from the server to the client in real-time, making it ideal for applications that require live data.
Useful DevTools Tips and Tricks#
This article discusses 15 popular tips for improving debugging efficiency using browser developer tools. These tips include zooming the developer tools interface, removing annoying overlays on web pages, listing fonts used on the page, measuring arbitrary distances on the page, detecting unused code, changing video playback speed, using developer tools in different languages, disabling event listeners, and more. The article provides step-by-step instructions for each tip and encourages readers to share their own tips in the comments section.
- Some popular developer tools tips include zooming the UI interface, removing annoying overlays, listing fonts used on the page, measuring arbitrary distances, detecting unused code, changing video playback speed, and using developer tools in different languages.
- Browser developer tools offer a range of panels and features that can significantly enhance your debugging workflow and efficiency.
- By exploring and utilizing these lesser-known features, you can optimize your debugging process and resolve common issues more effectively.
An Introduction to Command Injection Vulnerabilities in Node.js and JavaScript#
This article discusses command injection security vulnerabilities in Node.js and JavaScript applications. Command injection occurs when the operating system executes untrusted user input as a command, allowing attackers to gain unauthorized access or compromise the system. The article highlights the risks and impacts of command injection and provides several best practices to mitigate these vulnerabilities, including input validation and sanitization, separating commands from parameters, limiting command execution, and following the principle of least privilege. The article also recommends a book for further learning on how to protect Node.js applications from command injection vulnerabilities.
- Command injection vulnerabilities in Node.js and JavaScript applications can lead to unauthorized access, data breaches, or complete system compromise.
- To mitigate the risk of command injection vulnerabilities, it is crucial to implement input validation and sanitization, separate commands from parameters, avoid executing user-provided input as part of command execution, and follow the principle of least privilege.
- Understanding the risks, referencing real-world incidents, and following best practices can help developers effectively protect their Node.js applications from command injection vulnerabilities.
Tools#
typesafe-router#
A small wrapper library for React Router that significantly enhances type safety.
panda.css#
CSS-in-JS with build-time generated styles, RSC compatibility, multi-variant support, and a top-notch developer experience.
webperf-snippets#
Web performance snippets.
ModHeader - Modify HTTP headers#
Modify request and response headers.
tween.js#
JavaScript/TypeScript animation engine.
psd#
A fast zero-dependency PSD parser for Web and Node.js.
Updates#
styled-component v6#
remix 1.18#
nestjs v10#
NestJS 10 has been released, bringing bug fixes, improvements, and new features. This version introduces the use of SWC (Speedy Web Compiler) to speed up development. Module coverage can now be done in tests, making mocking easier. NestJS 10 supports Redis wildcard subscriptions, allowing subscriptions to messages that match a given pattern. The CacheModule has been moved to a standalone package. Node.js v12 is no longer supported, requiring the use of TypeScript v4.8 or higher for CLI plugins. Migration guides for upgrading from Nest v9 are available. NestJS projects offer enterprise consulting and support services. Community and sponsor support is crucial for the project's development.
- NestJS 10 introduces SWC (Speedy Web Compiler) to accelerate the development process, significantly improving the speed of the default TypeScript compiler.
- The new version allows module coverage in tests, making it easier to mock entire modules rather than just individual providers.
- NestJS 10 now supports Redis wildcard subscriptions, enabling users to subscribe to messages that match specific patterns.
Design#
Pure Dry Goods! How to Use Incentive Systems to Enhance User Stickiness#
This article mainly discusses the design and application of user incentive systems. User incentive systems are common means to promote user growth and activity, divided into platform spirit incentives, material benefit incentives, and social emotional incentives. A good incentive system can act like a conductor's baton, motivating users to grow in a specified direction, serving as a powerful tool for user growth and recall, and stimulating user activity. The incentive system accompanies the entire user growth process of "acquisition-activation-retention-referral-monetization," and different incentive methods can assist products in quickly achieving their goals. The article also analyzes the user demographics of a popular video platform and proposes ideas for redesigning an incentive system that aligns with the characteristics of its user base.
Exploring Universal And Cognitive-Friendly UX Design Through Pivot Tables And Grids#
This article discusses the importance of creating inclusive and user-friendly table designs. It focuses on the impact of cognitive disabilities on table perception and offers suggestions for improving table usability. The article emphasizes the necessity of reducing cognitive load, maximizing the signal-to-noise ratio, and effectively utilizing cognitive biases. It also discusses the role of color palettes and their use in table design. The overall goal is to create tables that are easy for all users to understand and navigate.
- Tables are a popular way to visualize data, but they can be difficult for individuals with cognitive disabilities to understand, making inclusive design crucial.
- When designing tables, cognitive load, cognitive biases, and the signal-to-noise ratio should be considered to ensure a good user experience for all users.
- Proper use of color in tables is important, as color conveys information and emotion, affecting how information is perceived.
AI#
GPT-4's Secret Has Been Revealed#
OpenAI's GPT-4 language model was highly anticipated, but the recent release disappointed many as it revealed that it is actually a collection of eight smaller models rather than a groundbreaking innovation. This approach, known as the expert mixture paradigm, was successfully used by Google engineers in 2021. However, OpenAI's marketing strategy successfully created a mystique and hype around the model, leading people to believe it possessed magical capabilities and preventing competitors from mimicking their technology. Nevertheless, GPT-4 remains an impressive language model with excellent performance, even if it did not meet expectations for a significant breakthrough in artificial intelligence.
- GPT-4 is not a single large model but rather a clever combination of eight smaller models.
- To prevent loss of confidence in progress in the field and to prevent competitors from mimicking their technology, OpenAI concealed the fact that GPT-4 is not a groundbreaking innovation.
- GPT-4 is a prime example of commercial marketing, hiding its less impressive aspects while maintaining high topical interest and enhancing its aura of mystery.
AI Tool Search Engine#
langtale.ai#
🚀 Introducing LangTale Playground langtale.ai/playground - the world's first playground supporting OpenAI function callings. This tool aims to allow developers and AI enthusiasts to experiment with the latest features of OpenAI, without writing a single line of code. 🧵1/6
Playground supporting OpenAI function calls.
ChatALL#
Chat simultaneously with ChatGPT, Bing Chat, Bard, Alpaca, Vicuna, Claude, ChatGLM, MOSS, iFlytek Spark, Wenxin Yiyan, etc., to discover the best answers.
Others#
The purpose of life is not for food and energy, but for negative entropy, striving for maximum negative entropy.
Entropy represents aging and death, while negative entropy represents the fight against aging and death.
-- Wikipedia entry "Entropy and Life"
Whenever you have a feeling that "someone should be doing something here," that someone is probably you.
-- "The Path of a Senior Engineer"