海外TECH |
MakeUseOf |
Are Your Windows 11 Desktop Icons Shrinking? Here's How to Fix That |
https://www.makeuseof.com/windows-11-desktop-icons-shrinking/
|
desktop |
2023-05-21 19:15:18 |
海外TECH |
DEV Community |
React 18 server components deep dive |
https://dev.to/xakrume/react-server-components-deep-dive-29af
|
React server components deep diveReact Server Components RSC is a promising feature that can have a significant impact on page load performance bundle size and the way we write React applications This feature is still experimental in React but it s worth understanding how it works under the hood Separation of server and client componentsReact Server Components allows the server and client browser to work together to render your React application Some components in the React element tree are rendered by the server and some are rendered by the browser This is not the same as server side rendering SSR SSR simulates an environment for rendering a React tree into raw HTML but it does not distinguish between server and client components The React team has defined server and client components based on the extension of the file in which the component is written if the file ends in server jsx it contains server components if it ends in client jsx it contains client components If it ends in neither it contains components that can be used as both server and client components Life of an RSC RenderThe life of a page using RSC always begins on the server in response to an API call to render a React component The server then serializes the root component element into JSON The end goal here is to render the initial root server component into a tree of basic HTML tags and client component placeholders The server then sends this serialized tree to the browser and the browser can do the work of deserializing it filling the client placeholders with the actual client components and rendering the end result RSC and SuspenseSuspense plays an important role in RSC Suspense allows you to throw promises from your React components when they need something that is not yet ready fetching data lazily importing components etc These promises are captured at the suspense boundary When a promise is thrown from rendering a Suspense subtree React stops rendering that subtree until the promise is resolved and then tries again RSC Wire FormatThe server outputs a simple format with a JSON blob on each line tagged with an ID This format is very streamable once the client has read a full line it can parse a snippet of JSON and make some progress Consuming the RSC FormatThe react server dom webpack package contains the entrypoints that take the RSC response and rebuild the React element tree When the server finishes loading the data it outputs the rows for the module reference which defines the module reference to the component and the React element tree that should be swapped into where the reference is RSC vs Fetching Data from Client ComponentsWhether RSC is better than fetching data from client components depends on what you are rendering to the screen With RSC you get denormalized processed data that maps directly to what you are showing to the user If the rendering requires multiple data fetches that depend on each other in a waterfall then it is better to do the fetching on the server where data latency is much lower than from the browser RSC and SSRWith React it is possible to combine both SSR and RSC so you can generate HTML on the server and then hydrate that HTML with RSC in the browser Server Side Rendering SSR Server side rendering SSR is a technique where a React application is rendered on the server into a static HTML string which is then sent to the client This can improve performance and SEO by allowing the page to be displayed before all the JavaScript has been loaded and parsed import express from express import React from react import ReactDOMServer from react dom server import App from App const server express server get req res gt const appString ReactDOMServer renderToString lt App gt res send lt DOCTYPE html gt lt html gt lt head gt lt title gt My App lt title gt lt head gt lt body gt lt div id root gt appString lt div gt lt script src bundle js gt lt script gt lt body gt lt html gt server listen In this example the App component is rendered to a string on the server and that string is inserted into the HTML response The client then hydrates this static HTML into a fully interactive React application React Server Components RSC React Server Components RSC allow the server and client to work together to render a React application Some components render on the server and others render on the client This can improve performance by reducing the amount of JavaScript sent to the client and allowing the server to fetch and render data directly Here s a simple example of RSC Message server jsimport db from db server function Message id const message db messages get id return lt div gt lt h gt message title lt h gt lt p gt message body lt p gt lt div gt export default Message App client jsimport useState from react import Message from Message server function App const selectedId setSelectedId useState return lt div gt lt button onClick gt setSelectedId selectedId gt Next lt button gt lt Message id selectedId gt lt div gt export default App In this example the Message server component retrieves and renders a message based on an id prop The App client component maintains a piece of state selectedId and renders the Message server component with the current id Practical RecommendationsUnderstand the difference between server and client components Understanding which components are rendered by the server and which are rendered by the client is critical to using RSC effectively Use Suspense with RSC Suspense allows you to handle promises in your React components which is integral to the functioning of RSCOptimize for performance RSC can significantly improve page load performance and reduce bundle size However it s important to measure and monitor these metrics to ensure that you re getting the expected benefits Consider the tradeoffs While RSC offers many benefits it also comes with tradeoffs For example server components cannot use states or effects which can limit their use in certain scenarios Experiment with RSC in non critical parts of your application Given the experimental nature of RSC it may be a good idea to start experimenting with it in non critical parts of your application This will give you a better understanding of how it works and how it can be used effectively Combine RSC with other React features RSC can be combined with other React features like Suspense and Concurrent Mode to build more efficient and user friendly applications Examples Let s look at some code examples to illustrate how React Server Components RSC work First let s define a server component Server components are identified by the server js extension Message server jsimport db from db server function Message id const message db messages get id return lt div gt lt h gt message title lt h gt lt p gt message body lt p gt lt div gt export default Message In this example Message is a server component that fetches a message from a database based on an id prop Notice that we re directly importing a server module db server and using it to fetch data You can t do this in a client component Next let s define a client component that uses this server component App client jsimport useState from react import Message from Message server function App const selectedId setSelectedId useState return lt div gt lt button onClick gt setSelectedId selectedId gt Next lt button gt lt Message id selectedId gt lt div gt export default App In this example App is a client component that maintains a piece of state selectedId and renders the Message server component with the current id When the Next button is clicked the selectedId is incremented causing the Message component to be rendered again with the new id This is a simple example but it illustrates the key idea behind RSC server components can be used to fetch and render data on the server while client components maintain interactivity on the client ComparisonWhile both SSR and RSC involve rendering on the server they serve different purposes and have different tradeoffs SSR is primarily concerned with improving performance and SEO by sending static HTML to the client However it requires sending all JavaScript to the client which can be large and slow to parse RSC on the other hand allows the server and client to collaborate on rendering which can reduce the amount of JavaScript sent to the client and improve performance However server components cannot use states or effects which can limit their use in certain scenarios In summary both SSR and RSC are powerful techniques for rendering React applications each with its own strengths and tradeoffs Understanding these differences can help you make more informed decisions about which technique to use in your projects Links react server components |
2023-05-21 19:50:21 |
海外TECH |
DEV Community |
Rust Trait Implementation Wizardry 🧙: Unveiling the Magic of Macro Rules |
https://dev.to/cleggacus/rust-trait-implementation-wizardry-unveiling-the-magic-of-macro-rules-2p0f
|
Rust Trait Implementation Wizardry Unveiling the Magic of Macro RulesIMPORTANT This article will be a continuation of my previous article about rust traits So go quickly read it first if you need to understand rust traits The best TRAIT of RUST no pun intended IntroductionIf you have ever used rust it may seem like you have to rewrite a lot of code due to how the only way you can add repeatable functionality is through composing your structs with traits Well lucky for you there is this amazing feature called macros What is a macro in rust Macros can help use write a function that generates code at compile time Using macros can make you a much faster programmer since you can write a macro that will implement traits for you meaning you don t have to keep doing the tedious task of rewriting your implementation over and over again There are main types of macros in rust declarative and procedural Declarative macros in rust are usually referred to as macro rules since they are created but typing macro rules On the other hand procedural macros are used for directly accessing the token stream to consume and produce syntax in rust Procedural macros are used through the proc macro crate and are not going to be the focus of this article For this article we will be using macro rules since they are builtin without having to add any crates and are much simpler to create Let s start coding For this example we will be continuing from the last article about rust traits If you wish to follow along you can grab the code from GitHub Best trait of rust repository What is a number So far we have said that to create a Vec for type T it must implement the Add trait This is so that Vec can be also used for addition Since we need lots more operations we can define a number trait to make things a little easier pub trait Number Clone Copy Sized Add lt Output Self gt Sub lt Output Self gt Div lt Output Self gt Mul lt Output Self gt AddAssign SubAssign DivAssign MulAssign This trait might not have any direct functionality but it does mean when ever we want to say that a generic has all the other necessary trait we just have to say it implements number This now means that we will need to implement number for all the number types The first thought might be to write it out like this impl Number for f impl Number for f impl Number for u impl Number for u impl Number for u impl Number for i impl Number for i impl Number for i Now this isn t to bad and it might be the way you would prefer to write your code since it is more verbose But for the sake of this article we will make this less verbose through macro rules First we think of how we wish the macro rule to look To make the code super simple we can have a macro rule named impl number with a list of types that will implement number It will look something like this impl number usize f f u u u i i i To create a macro we start with macro rules followed by the name of the macro impl number macro rules impl number code goes here We now need need to actually create a the code to generate the line impl Number for type name here To do this we create a function that takes the designator ty which is used for types A designator is basically just the type of thing you are passing to the macro The matcher will be written as t ty where t is the argument name and ty is the designator type We can then simply write in the function the code we wish to generate So in this case impl Number for t To impliment a single type for a trait would look like this macro rules impl number t ty gt impl Number for t So this is great and all but this only implements one type To allow a list of arguments to be passed we need surround the matcher with If we wish to repeat the generated code for each argument we can surround the code with All together this will look like the following macro rules impl number t ty gt impl Number for t We can now below this write the following to actually implement the types impl number usize f f u u u i i i Now we can rewrite the Vec struct from this pub struct Vec lt T gt where T Add lt Output T gt Copy Clone pub x T pub y T To this derive Debug Copy Clone pub struct Vec lt T Number gt pub x T pub y T OperationsThere is mainly operations we wish to implement for the Vec struct The first is operators that create a new value and then there s operators that also assign the value In the previous article we looked at how the implement the Add trait and used the following code impl lt T gt Add for Vec lt T gt where T Add lt Output T gt Copy Clone type Output Vec lt T gt fn add self rhs Self gt Self Output Vec x self x rhs x y self y rhs y If we look at this implementation block there are only a couple things that change between operators The trait name changes and the function name changes Although the operator symbol also changes we can just call the method directly instead To implement this as a macro we will use the name impl vec op This will take designators an identifier for the trait and an identifier for the method name An identifier is represented by the keyword ident We can then replace the trait name with trait and the method name with func The completed macro rule looks like the following macro rules impl vec op trait ident func ident gt impl lt T Number gt trait for Vec lt T gt type Output Self fn func self rhs Self gt Self Output Vec x self x func rhs x y self y func rhs y We then run the macro with add sub div and mul with the following lines impl vec op Add add impl vec op Sub sub impl vec op Div div impl vec op Mul mul To show the benefits to this macro based approach lets say we now wish to allow adding a number T to a vector Vec lt T gt We can easily add the implementation block to the macro so that it is implemented for all the operations impl lt T Number gt trait lt T gt for Vec lt T gt type Output Self fn func self rhs T gt Self Output Vec x self x func rhs y self y func rhs Altogether the macro would look like this macro rules impl vec op trait ident func ident gt impl lt T Number gt trait for Vec lt T gt type Output Self fn func self rhs Self gt Self Output Vec x self x func rhs x y self y func rhs y impl lt T Number gt trait lt T gt for Vec lt T gt type Output Self fn func self rhs T gt Self Output Vec x self x func rhs y self y func rhs We can now similarly do this for the assignment operators with the following macro rule macro rules impl vec op assign trait ident func ident gt impl lt T Number gt trait for Vec lt T gt fn func amp mut self rhs Self self x func rhs x self y func rhs y impl lt T Number gt trait lt T gt for Vec lt T gt fn func amp mut self rhs T self x func rhs self y func rhs impl vec op assign AddAssign add assign impl vec op assign SubAssign sub assign impl vec op assign DivAssign div assign impl vec op assign MulAssign mul assign Finally we can update our ToVec trait For this we will instead use the From trait since it is included in the standard library Since we have a generic we do not need to create a macro rule for this impl lt T Number gt From lt T gt for Vec lt T gt fn from val T gt Self Vec x val y val Lets quickly write a testWe first need to implement partial equals for the Vec struct This is simple We just need to add it to number and then derive it in Vec pub trait Number PartialEq derive Debug Copy Clone PartialEq pub struct Vec lt T Number gt Note I removed the main rs file from the previous articleWe can then write our test in lib rs as follows pub mod vec cfg test mod tests use crate vec Vec test fn it works let v Vec lt i gt into let v Vec x y let mut v v v v Vec from assert eq v Vec x y We can now run the test with cargo testAnd we get the following output IT WORKS Find the full code here Trait Implementation Wizardry ChallengeTry and write some macros for casting between numbers using the from trait ConclusionWe have explored how to fix the issue with repeating trait implementation blocks by using macro rules and how we can practically do this with the Vec example from the previous article If you have any questions leave a comment and it would be much appreciated if you drop a like if you enjoyed this article thanks |
2023-05-21 19:49:23 |
海外TECH |
DEV Community |
Git things: Renaming your working branch |
https://dev.to/simhskal/git-things-renaming-your-working-branch-4a05
|
Git things Renaming your working branchI drafted this post years ago and never hit Publish As a developer I have been working with various proprietary tools for most of my professional life Recently I started working on some personal projects where I needed to use Git an open source tool for version control I have to admit I made silly mistakes while navigating Git at first But with some practice and research I have learned how to use it effectively Something I struggled with initially was renaming a working branch in Git It s a common task that developers need to do quite often but I found it challenging initially After some research and experimentation I have come up with a goto guide Here is my step by step guide to rename a working branch in Git on both local and remote setups Renaming a branch locallyFirst navigate to the local branch that you want to rename using the command git checkout lt branch name gt Then rename the branch using the command git branch m lt new branch name gt This will rename the current branch to the new branch name Pushing renamed branch to remoteAfter renaming the branch locally push the changes to the remote repository using the command git push origin u lt new branch name gt This will push the renamed branch to the remote repository Deleting old branch on remoteIf you want to delete the old branch from the remote repository use the command git push origin delete lt old branch name gt This will delete the old branch from the remote repository That s it You have successfully renamed a working branch in Git on both local and remote setups Happy coding |
2023-05-21 19:30:37 |
Apple |
AppleInsider - Frontpage News |
How to build your own working Apple I replica computer |
https://appleinsider.com/articles/23/05/21/how-to-build-your-own-working-apple-i-replica-computer?utm_medium=rss
|
How to build your own working Apple I replica computerRetro computing lets you get to grips with technology s history showing how far modern computers have come Here s how to build your own working Apple I replica Computers have come a long way since Apple first started in In those days when Steve Jobs and Steve Wozniak first put together the original Apple I computer kits everything was sourced and assembled by hand Apple was a tiny company based in Steve Jobs parents garage and Apple sold kit computers out of the garage Read more |
2023-05-21 19:48:14 |
海外TECH |
CodeProject Latest Articles |
Machine Learning Basics and Perceptron Learning Algorithm |
https://www.codeproject.com/Articles/1211753/Machine-Learning-Basics-and-Perceptron-Learning-Al
|
algorithm |
2023-05-21 19:37:00 |
ニュース |
BBC News - Home |
Rishi Sunak to meet ethics adviser over Suella Braverman speeding claims |
https://www.bbc.co.uk/news/uk-politics-65659053?at_medium=RSS&at_campaign=KARANGA
|
attorney |
2023-05-21 19:30:47 |
ニュース |
BBC News - Home |
Greek election: Centre-right Mitsotakis heads for victory short of majority |
https://www.bbc.co.uk/news/world-europe-65666261?at_medium=RSS&at_campaign=KARANGA
|
outright |
2023-05-21 19:09:55 |
ニュース |
BBC News - Home |
Manchester City 1-0 Chelsea: Pep Guardiola says his side's third successive title 'extraordinary' |
https://www.bbc.co.uk/sport/av/football/65635503?at_medium=RSS&at_campaign=KARANGA
|
Manchester City Chelsea Pep Guardiola says his side x s third successive title x extraordinary x Manchester City manager Pep Guardiola says his side s third successive Premier League title win is extraordinary after their victory over Chelsea |
2023-05-21 19:16:29 |
ニュース |
BBC News - Home |
Manchester United 2-1 Manchester City: Late goal keeps Red Devils' WSL title hopes alive |
https://www.bbc.co.uk/sport/football/65586930?at_medium=RSS&at_campaign=KARANGA
|
Manchester United Manchester City Late goal keeps Red Devils x WSL title hopes aliveLucia Garcia scores an injury time winner in a dramatic derby to keep Manchester United s faint Women s Super League title hopes alive |
2023-05-21 19:52:35 |
ビジネス |
ダイヤモンド・オンライン - 新着記事 |
九州・沖縄で富裕層が住む地域ランキング【相続税納税額で判定】2位博多、1位は? - シン富裕層の投資・節税・相続 |
https://diamond.jp/articles/-/321977
|
日本全国 |
2023-05-22 04:50:00 |
ビジネス |
ダイヤモンド・オンライン - 新着記事 |
「激安企業」の淘汰始まる!金融庁と東証がPBR1倍割れ是正の次に狙う改革案が判明 - 激安株を狙え |
https://diamond.jp/articles/-/323127
|
東京証券取引所 |
2023-05-22 04:45:00 |
ビジネス |
ダイヤモンド・オンライン - 新着記事 |
「激安株」を狙え!PBR1倍割れでキャッシュリッチな銘柄に“株主圧力”が迫る - 激安株を狙え |
https://diamond.jp/articles/-/323126
|
|
2023-05-22 04:40:00 |
ビジネス |
ダイヤモンド・オンライン - 新着記事 |
【無料公開】マニュライフ生命の子会社代理店も内部崩壊、「親会社の商品を売れ!」の方針転換に非難囂々 - Diamond Premiumセレクション |
https://diamond.jp/articles/-/323173
|
機能不全 |
2023-05-22 04:30:00 |
ビジネス |
ダイヤモンド・オンライン - 新着記事 |
1ドル138円まで上昇も方向感に欠けるドル円相場、「どっち付かず」が続く理由 - 政策・マーケットラボ |
https://diamond.jp/articles/-/323202
|
年初来安値 |
2023-05-22 04:25:00 |
ビジネス |
ダイヤモンド・オンライン - 新着記事 |
日本人はなぜ「醜くても勝つ」より「美しく負ける」を選ぶのか? - 要約の達人 from flier |
https://diamond.jp/articles/-/323171
|
日本人はなぜ「醜くても勝つ」より「美しく負ける」を選ぶのか要約の達人fromflier「日本人は空気を読む」と言われることがある。 |
2023-05-22 04:20:00 |
ビジネス |
ダイヤモンド・オンライン - 新着記事 |
年収が低い会社ランキング2022最新版【平均年齢40代・従業員100人未満】200万円台の3社は? - ニッポンなんでもランキング! |
https://diamond.jp/articles/-/323075
|
上場企業 |
2023-05-22 04:15:00 |
ビジネス |
ダイヤモンド・オンライン - 新着記事 |
年収が低い会社ランキング2022最新版【平均年齢40代・従業員100人未満】300社完全版 - ニッポンなんでもランキング! |
https://diamond.jp/articles/-/323074
|
上場企業 |
2023-05-22 04:15:00 |
ビジネス |
ダイヤモンド・オンライン - 新着記事 |
半導体よりヤバい電池欠乏危機!自動車メーカーが覚悟すべき「EV電池投資額」を初試算 - 今週の週刊ダイヤモンド ここが見どころ |
https://diamond.jp/articles/-/323228
|
そこでダイヤモンド編集部では、世界のEV生産が万台に達した時に必要となるEV電池投資額を初試算しました。 |
2023-05-22 04:10:00 |
ビジネス |
ダイヤモンド・オンライン - 新着記事 |
出社かリモートかせめぎ合い…「全員同じ働き方」を求める日本企業の限界 - 組織の病気~成長を止める真犯人~ 秋山進 |
https://diamond.jp/articles/-/323064
|
出社かリモートかせめぎ合い…「全員同じ働き方」を求める日本企業の限界組織の病気成長を止める真犯人秋山進コロナ禍がついに「終焉」し、リモートワークと対面ワークのせめぎ合いが発生しています。 |
2023-05-22 04:05:00 |
ビジネス |
東洋経済オンライン |
G7で大活躍、JR西「観光船シースピカ」誕生の秘密 地元海運会社と共同開発し瀬戸内海クルーズ | 経営 | 東洋経済オンライン |
https://toyokeizai.net/articles/-/673905?utm_source=rss&utm_medium=http&utm_campaign=link_back
|
東洋経済オンライン |
2023-05-22 04:30:00 |
コメント
コメントを投稿