970 Matching Annotations
  1. Aug 2021
    1. We can even say that server caching tools like React-Query, SWR, Apollo, and Urql fit the definition of "state management" - they store initial values based on the fetched data, return the current value via their hooks, allow updates via "server mutations", and notify of changes via re-rendering the component
    1. but in a more practical scenario, you often suffer from "death by a thousand cuts" which means that there's not really a single place that's slow, so you wind up applying React.memo everywhere. And when you do that, you have to start using useMemo and useCallback everywhere as well (otherwise you undo all the work you put into React.memo). Each of these optimizations together may solve the problem, but it drastically increases the complexity of your application's code and it actually is less effective at solving the problem than colocating state because React does still need to run through every component from the top to determine whether it should re-render. You'll definitely be running more code with this approach, there's no way around that.
    1. I consistently see developers putting all of their state into redux. Not just global application state, but local state as well. This leads to a lot of problems, not the least of which is that when you're maintaining any state interaction, it involves interacting with reducers, action creators/types, and dispatch calls, which ultimately results in having to open many files and trace through the code in your head to figure out what's happening and what impact it has on the rest of the codebase.
    1. How to Make a React Progressive Web Application (PWA)Eugene VolkovFrontend DeveloperKate KikidzhanCloud & SaaS Product ResearcherReactJavaScriptPWAHomeBlogDevelopmentHow to Make a React Progressive Web Application (PWA)Oct 7, 202021 min readThe early bird catches the worm. But the situation was not so favourable back in 2007 when Steve Jobs proposed the idea of web applications to be the model for iPhone Apps. Back then, the tech community was not yet ready to bring a huge interest in web apps. But since 2015, tech giants like Google and Microsoft have been preparing the tech ground for progressive web apps (or simply – PWAs). And now, PWA became a must-have technology for both giant corporations and small startups. Twitter, Starbucks, Google, and Aliexpress use progressive web apps to boost their online presence. At Codica, we have been helping our customers to develop their businesses by building robust PWA for our customers since 2015. That is why we have created this comprehensive guide on how to create a PWA with React. Also, you will see the most prominent progressive web app examples.

      The early bird catches the worm. But the situation was not so favourable back in 2007 when Steve Jobs proposed the idea of web applications to be the model for iPhone Apps. Back then, the tech community was not yet ready to bring a huge interest in web apps.

      But since 2015, tech giants like Google and Microsoft have been preparing the tech ground for progressive web apps (or simply – PWAs). And now, PWA became a must-have technology for both giant corporations and small startups. Twitter, Starbucks, Google, and Aliexpress use progressive web apps to boost their online presence.

      At Codica, we have been helping our customers to develop their businesses by building robust PWA for our customers since 2015. That is why we have created this comprehensive guide on how to create a PWA with React. Also, you will see the most prominent progressive web app examples.

  2. Jul 2021
  3. Jun 2021
    1. The ecosystem behind React gave you too many choices of this sort, which fragmented the tech stack and caused the infamous “Javascript fatigue”.

      To me, the reason React ruined web development is because it homogenized & centralized the practice, in an abstraction that is decoupled & non-interoperable with other techniques & styles.

      The author is arguing that React didn't centralize enough, but to me, it sucked all the oxygen out of the diverse interesting place that was web development. That it didn't try to solve all problems in the stack is, if anything, a most relief. It succeeded because it didn't bundle in a data-layer. It succeeded because it didn't bundle in state. It succeeded because it didn't bundle in routing. Each of these areas have evolved independently & seen great strides across the last half decade. That's a huge win, that's why React is so strong: because it didn't try to form opinions.

      Alas React itself implies a strong opinion, has a big abstraction that de-empowers & de-inter-operates with the DOM, that keeps it from working in concert with any other technology. It has enormous diversity, but only under it's own umbrella. It has crushed a much livelier sporting aspect of web development.

      I'm so tired of weenies complaining about fragmentation. Get lost and fuck off. This medium is flexible & diverse & interesting. Stop applying your industrial software want, your software authoritarianism, "why can't everyone just do it my way/the right way" horse shit. Such a shitty attitude, from people selling FUD & clutching at the idea that everyone's gonna be happy & productive if we can just make the right framework. How uncreative & droll.

  4. Mar 2021
    1. If I were to sum up why in one sentence, it's because I don't miss useEffect. I understand why it exists, I understand the approach React takes, and there are benefits of its approach. But writing complex React components feels more like admin; a constant worry that I'll miss a dependency in my useEffect call and end up crashing my browser session. With Svelte I don't have that lingering feeling, and that's what I've come to enjoy.
    2. Svelte is different in that by default most of your code is only going to run once; a console.log('foo') line in a component will only run when that component is first rendered.
    3. Here's where I start to have a preference for Svelte; the two are very similar but once I got used to Svelte I found that React felt like jumping through hoops. You can't create a worker instance, it has to go in a useRef, and then you can't easily pull code out into a function without then requiring useCallback so it can be a safe dependency on useEffect. With Svelte I write code that's closer to "plain" JavaScript, whereas in React more of my code is wrapped in a React primitive.
    1. 副作用内からなぜ関数を返したのか? これこそが副作用のクリーンアップのためのオプションの仕組みです。すべての副作用は、それをクリーンアップするための関数を返すことができます。これにより購読を開始するためのロジックと解除するためのロジックを並べて書くことができます。両方とも同じ副作用の一部なのです! React は具体的には副作用のクリーンアップをいつ発生させるのか? React はコンポーネントがアンマウントされるときにクリーンアップを実行します。しかし、すでに学んだ通り、副作用は 1 回だけでなく毎回のレンダー時に実行されます。このため React は、ひとつ前のレンダーによる副作用を、次回の副作用を実行する前にもクリーンアップします。この後で、これがなぜバグの回避につながるのか、そしてこれがパフォーマンスの問題を引き起こしている場合にどのようにしてこの挙動を止めるのかについて説明します。 補足 副作用から名前付きの関数を返す必要はありません。ここでは目的を明示するために cleanup という名前にしましたが、アロー関数を返すことも別の名前を付けることも可能です。 まとめ useEffect を用いることで、コンポーネントのレンダー後に実行される様々な種類の副作用を表現できることを学びました。いくつかの副作用はクリーンアップが必要である可能性があり、その場合は関数を返します: useEffect(() => { function handleStatusChange(status) { setIsOnline(status.isOnline); } ChatAPI.subscribeToFriendStatus(props.friend.id, handleStatusChange); return () => { ChatAPI.unsubscribeFromFriendStatus(props.friend.id, handleStatusChange); }; }); クリーンアップフェーズが必要ない副作用もあり、その場合は何も返す必要はありません。 useEffect(() => { document.title = `You clicked ${count} times`; }); 副作用フックは両方のユースケースをひとつの API に統合します。 副作用フックの動作について十分わかったと感じる場合や、逆にもううんざりだという場合は、ここで次のページ(フックのルールについて)に進んでも構いません。 副作用を使う場合のヒント このページの残りの部分では、経験のある React 利用者が興味を持つかもしれない useEffect の深い概念について説明します。今すぐ読み進める必要があるとは思わないでください。副作用フックについて詳細が知りたくなったらいつでもこのページに戻ってくればいいのです。 ヒント:関心を分離するために複数の副作用を使う フックを導入する動機のページで述べた問題のひとつは、しばしばそれぞれのライフサイクルメソッドに関連のないロジックが含まれ、一方で関連するロジックが複数のメソッドに分割されてしまう、ということです。以下に示すのは、これまでの例で挙げたカウンタとフレンド状態インジケータとを組み合わせたコンポーネントです。 class FriendStatusWithCounter extends React.Component { constructor(props) { super(props); this.state = { count: 0, isOnline: null }; this.handleStatusChange = this.handleStatusChange.bind(this); } componentDidMount() { document.title = `You clicked ${this.state.count} times`; ChatAPI.subscribeToFriendStatus( this.props.friend.id, this.handleStatusChange ); } componentDidUpdate() { document.title = `You clicked ${this.state.count} times`; } componentWillUnmount() { ChatAPI.unsubscribeFromFriendStatus( this.props.friend.id, this.handleStatusChange ); } handleStatusChange(status) { this.setState({ isOnline: status.isOnline }); } // ... ここで、document.title を設定するためのロジックが componentDidMount と componentDidUpdate に分離してしまっていることに注意してください。データ購読のためのロジックもやはり componentDidMount と componentWillUnmount とに分離しています。そして componentDidMount には両方の仕事のためのコードが含まれています。 ではフックはどのようにこの問題を解決するのでしょうか? ステートフックを複数回呼べるのと同様の方法で、副作用を複数回利用することができます。このため、互いに関係のないロジックは別の副作用に分離することが可能です。 function FriendStatusWithCounter(props) { const [count, setCount] = useState(0); useEffect(() => { document.title = `You clicked ${count} times`; }); const [isOnline, setIsOnline] = useState(null); useEffect(() => { function handleStatusChange(status) { setIsOnline(status.isOnline); } ChatAPI.subscribeToFriendStatus(props.friend.id, handleStatusChange); return () => { ChatAPI.unsubscribeFromFriendStatus(props.friend.id, handleStatusChange); }; }); // ... } フックを使うことで、ライフサイクルのメソッド名に基づくのではなく、実際に何をやっているのかに基づいてコードを分割できます。React はコンポーネントで利用されているすべての副作用を、指定されている順番で適用していきます。 解説:なぜ副作用は毎回の更新ごとに実行されるのか クラスに慣れていれば、なぜクリーンアップフェーズは、アンマウント時の 1 度だけではなく再レンダー時に毎回発生するのか、と不思議に思っているかもしれません。実践的な例で、この設計によりなぜバグの少ないコンポーネントが作れるようになるのか見てみましょう。 このページの前の部分で、フレンドがオンラインかどうかを表示する FriendStatus コンポーネントの例を示しました。このクラスでは this.props の中にある friend.id を参照して、コンポーネントがマウントした後にフレンドのステータスを購読し、アンマウント時には購読を解除します: componentDidMount() { ChatAPI.subscribeToFriendStatus( this.props.friend.id, this.handleStatusChange ); } componentWillUnmount() { ChatAPI.unsubscribeFromFriendStatus( this.props.friend.id, this.handleStatusChange ); } ですがコンポーネントが表示されている最中に friend プロパティが変わったらどうなるのでしょうか? このコンポーネントは間違ったフレンドのオンラインステータスを表示し続けてしまいます。これはバグです。しかも誤ったフレンド ID を使って購読解除を呼び出してしまうため、アンマウント時にメモリリークやクラッシュを引き起こしてしまうでしょう。 クラスコンポーネントの場合は、このようなケースに対処するために componentDidUpdate を加える必要がありました。 componentDidMount() { ChatAPI.subscribeToFriendStatus( this.props.friend.id, this.handleStatusChange ); } componentDidUpdate(prevProps) { // Unsubscribe from the previous friend.id ChatAPI.unsubscribeFromFriendStatus( prevProps.friend.id, this.handleStatusChange ); // Subscribe to the next friend.id ChatAPI.subscribeToFriendStatus( this.props.friend.id, this.handleStatusChange ); } componentWillUnmount() { ChatAPI.unsubscribeFromFriendStatus( this.props.friend.id, this.handleStatusChange ); } 適切な componentDidUpdate 処理をし忘れることが、React アプリケーションにおけるよくあるバグの原因となっていました。 ではこのコンポーネントのフックを利用したバージョンを見てみましょう。 function FriendStatus(props) { // ... useEffect(() => { // ... ChatAPI.subscribeToFriendStatus(props.friend.id, handleStatusChange); return () => { ChatAPI.unsubscribeFromFriendStatus(props.friend.id, handleStatusChange); }; }); 動作は変わっておらず、前述のバグも起こらなくなります。 useEffect はデフォルトで更新を処理するため、更新のための特別なコードは不要です。新しい副作用を適用する前に、ひとつ前の副作用をクリーンアップします。これを例示するため、このコンポーネントが経時的に発生させる可能性のある購読登録と購読解除のシーケンスを示します: // Mount with { friend: { id: 100 } } props ChatAPI.subscribeToFriendStatus(100, handleStatusChange); // Run first effect // Update with { friend: { id: 200 } } props ChatAPI.unsubscribeFromFriendStatus(100, handleStatusChange); // Clean up previous effect ChatAPI.subscribeToFriendStatus(200, handleStatusChange); // Run next effect // Update with { friend: { id: 300 } } props ChatAPI.unsubscribeFromFriendStatus(200, handleStatusChange); // Clean up previous effect ChatAPI.subscribeToFriendStatus(300, handleStatusChange); // Run next effect // Unmount ChatAPI.unsubscribeFromFriendStatus(300, handleStatusChange); // Clean up last effect この挙動によりデフォルトで一貫性を保証することができ、クラスコンポーネントでよく見られた更新ロジック書き忘れによるバグを防止することができます。 ヒント:副作用のスキップによるパフォーマンス改善 いくつかの場合では、副作用のクリーンアップと適用とをレンダーごとに毎回行うことはパフォーマンスの問題を引き起こす可能性があります。クラスコンポーネントの場合、この問題は componentDidUpdate の内部で prevProps や prevState と比較するコードを加えることで解決できました。 componentDidUpdate(prevProps, prevState) { if (prevState.count !== this.state.count) { document.title = `You clicked ${this.state.count} times`; } } これはよくある要求なので、useEffect フックの API にはこの動作が組み込まれています。再レンダー間で特定の値が変わっていない場合には副作用の適用をスキップするよう、React に伝えることができるのです。そのためには、useEffect のオプションの第 2 引数として配列を渡してください。 useEffect(() => { document.title = `You clicked ${count} times`; }, [count]); // Only re-run the effect if count changes 上記の例では、第 2 引数として [count] を渡しています。どういう意味でしょうか? もし count が 5 で、次回のコンポーネントのレンダー時にも count がまだ 5 であった場合、React は前回のレンダー時に覚えておいた [5] と今回のレンダーの [5] とを比較します。配列内のすべての要素が同一 (5 === 5) ですので、React は副作用をスキップします。これが最適化です。 再レンダー時に count が 6 に変更されている場合、前回レンダー時に覚えておいた [5] と今回のレンダー時の [6] という配列とを比較します。今回は 5 !== 6 ですので React は副作用を再適用します。配列内に複数の要素がある場合、React は配列内の要素のうちひとつでも変わっている場合に副作用を再実行します。 クリーンアップフェーズがある副作用でも同様に動作します: useEffect(() => { function handleStatusChange(status) { setIsOnline(status.isOnline); } ChatAPI.subscribeToFriendStatus(props.friend.id, handleStatusChange); return () => { ChatAPI.unsubscribeFromFriendStatus(props.friend.id, handleStatusChange); }; }, [props.friend.id]); // Only re-subscribe if props.friend.id changes 将来的には、ビルド時の変換で第 2 引数を自動で加えられるようになるかもしれません。 補足 この最適化を利用する場合、時間の経過とともに変化し副作用によって利用される、コンポーネントスコープの値(props や state など)がすべて配列に含まれていることを確認してください。さもないとあなたのコードは以前のレンダー時の古い値を参照してしまうことになります。その他の最適化のオプションについてはフック API リファレンスで説明しています。 もしも副作用とそのクリーンアップを 1 度だけ(マウント時とアンマウント時にのみ)実行したいという場合、空の配列 ([]) を第 2 引数として渡すことができます。こうすることで、あなたの副作用は props や state の値のいずれにも依存していないため再実行する必要が一切ない、ということを React に伝えることができます。これは特別なケースとして処理されているわけではなく、依存配列を普通に処理すればそうなるというだけの話です。 空の配列 ([]) を渡した場合、副作用内では props と state の値は常にその初期値のままになります。[] を渡すことはおなじみの componentDidMount と componentWillUnmount による概念と似ているように感じるでしょうが、通常はこちらやこちらのように、副作用を過度に再実行しないためのよりよい解決方法があります。また useEffect はブラウザが描画し終えた後まで遅延されますので、追加の作業をしてもそれほど問題にならないということもお忘れなく。 eslint-plugin-react-hooks パッケージの exhaustive-deps ルールを有効にすることをお勧めします。これは依存の配列が正しく記述されていない場合に警告し、修正を提案します。 次のステップ おめでとうございます! 長いページでしたが、最終的に副作用に関するほとんどの疑問が解決していることを望みます。これでステートフックと副作用フックの両方を学んだので、それらを組み合わせてやれることがたくさんあります。クラスコンポーネントにおけるほとんどのユースケースがカバーされていますが、足りない部分については他のフックが役立つかもしれません。 また、動機のところで述べた問題をフックがどのように解決するのかについてもわかり始めてきたでしょう。副作用のクリーンアップがどのようにして componentDidUpdate と componentWillUnmount との間でのコードの重複を防ぎ、関係したコードを並べて書くことができるようにし、バグの少ないコードを記述できるようにするのかを見てきました。また目的別に副作用を分割する方法も学びましたが、これはクラスでは全く不可能なことでした。 この時点で、一体フックがどのように動作しているのか疑問に感じているかもしれません。useState のそれぞれの呼び出しがどの state 変数に対応しているのかを、React はどのようにして知るのでしょうか? 更新のたびに、前回と今回の副作用とを React はどのように対応付けるのでしょうか? 次のページではフックのルールについて学びます — このルールはフックが動作するために必須のものです。Is this page useful?このページを編集する

      useEffectで返されている関数は、 クラスコンポーネントにおけるcomponentWillUnmountの部分に実装する処理を書く部分だと理解しておけば良さそう。 つまり、コンポーネントがアンマウントされるときに実行される

    1. What are the current trends in JavaScript development?

      Performance, speed, or popularity? What are the most vital characteristics that developers seek in the tech stack? There could hardly be a single reason why certain frameworks rise, while others become the thing of the past.

      What you can do is to observe the driving directions within the front-end landscape. So let’s dive into the top JavaScript trends to watch in 2021.

  5. Feb 2021
  6. Jan 2021
  7. Dec 2020
  8. Nov 2020
    1. Frontend frameworks are a positive sum game! Svelte has no monopoly on the compiler paradigm either. Just like I think React is worth learning for the mental model it imparts, where UI is a (pure) function of state, I think the frontend framework-as-compiler paradigm is worth understanding. We're going to see a lot more of it because the tradeoffs are fantastic, to where it'll be a boring talking point before we know it.
  9. Oct 2020
  10. react-spectrum.adobe.com react-spectrum.adobe.com
    1. suite of over 30 separate packages of React visualization primitives that fall into several categories (Figure 2). It is un-opinionated on state management, animation, and styling so it can integrate with any React codebase, and its emphasis on modularity (similar to D3) lets you keep your bundle sizes down by only using the packages you need to create your reusable chart library or a custom one-off chart.

      Short definition of visx

    2. In our research (Figure 1), we found that existing React visualization libraries are often high-level abstractions and optimized for ease of use (i.e., fewer lines of code) at the expense of expressivity. None offer the expressivity of D3 primitives and many don’t allow for the optimization we want in production because computation, animations, state management, styles, and rendering are all encapsulated.

      Comparison of data visualisation libraries:

    3. because D3 and React both want to own DOM manipulation, we’ve found that it’s best to only use D3 for the math and React for the DOM because two mental models for updating the DOM opens the door for bugs to sneak in. However, using D3 solely for math means a significant amount of its (DOM-based) functionality is not available for use: selection.join, zoom, drag, brush, and transitions. Additionally, as mentioned above, D3 has its own learning curve and we would like developers to feel like they are writing native React code with standard APIs and familiar patterns.

      You can use D3 inside a React app, but...

    1. You should not create a new debounce function on every render with: return new Promise(resolve => { debounce(() => resolve(this.getIsNameUnique(name)), 2000); }); Instead you should just wrap your whole function isNameUnique with the debounce (see my sandbox). By creating a new debounce function on every hit, it cannot 'remember' that is was called or that is will be called again. This will prevent the debouncing.
    1. In React 0.12 time frame we did a bunch of small changes to how key, ref and defaultProps works. Particularly, they get resolved early on in the React.createElement(...) call. This made sense when everything was classes, but since then, we've introduced function components. Hooks have also make function components more prevalent. It might be time to reevaluate some of those designs to simplify things (at least for function components).
    2. In the next major, we'll start copying the ref onto both the props and the element.ref. React will now use the props.ref as the source of truth for forwardRef and classes and it will still create a shallow copy of props that excludes the ref in these cases. At the same time, we'll add a getter for element.ref in DEV that warns if you access it. The upgrade path is now to just access it off props if you need it from the element.
    1. Facebook’s React has an optional language extension that enables you to embed HTML inside JavaScript. This extension can make your code more concise, but it also breaks compatibility with the rest of the JavaScript ecosystem. ECMAScript 6 will have template strings [1], which enable you to implement JSX (or something close to it) inside the language.
    1. You want to write maintainable tests that give you high confidence that your components are working for your users. As a part of this goal, you want your tests to avoid including implementation details so refactors of your components (changes to implementation but not functionality) don't break your tests and slow you and your team down.

      key point. I think that this also means that NOT using data-testid is better since this is "testing library" specific attribute and 'binds' us to testin-library

    1. For any element that isn't there yet but will be there eventually, use findBy over getBy or queryBy. If you assert for a missing element, use queryBy. Otherwise default to getBy

      key point: summary of getBy, queryBy and findBy

    2. The neat thing about getByRole: it shows all the selectable roles if you provide a role that isn't available in the rendered component's HTML:

      pass no arguments and it will list all available roles in the element you passed to it (including implicit roles)

    3. Whereas the describe-block is the test suite, the test-block (which also can be named it instead of test) is the test case. A test suite can have multiple test cases and a test case doesn't have to be in a test suite. What you put into the test cases are called assertions (e.g. expect in Jest) which either turn out to be successful (green) or erroneous (red). Here we have two assertions which should turn out successful:

      Key point explaining key basic terms in React testign world

    1. It's possible to run a function whenever some reactive state changes using the useEffect hook. In the example we log the length of the todoList whenever it changes. The first argument to useEffect is the function we want to run, and the second is a list of reactive values to track - whenever one of these values changes the effect will run again.
  11. Sep 2020
    1. I think Svelte's approach where it replaces component instances with the component markup is vastly superior to Angular and the other frameworks. It gives the developer more control over what the DOM structure looks like at runtime—which means better performance and fewer CSS headaches, and also allows the developer to create very powerful recursive components.
    1. The more I think about this, the more I think that maybe React already has the right solution to this particular issue, and we're tying ourselves in knots trying to avoid unnecessary re-rendering. Basically, this JSX... <Foo {...a} b={1} {...c} d={2}/> ...translates to this JS: React.createElement(Foo, _extends({}, a, { b: 1 }, c, { d: 2 })); If we did the same thing (i.e. bail out of the optimisation allowed by knowing the attribute names ahead of time), our lives would get a lot simpler, and the performance characteristics would be pretty similar in all but somewhat contrived scenarios, I think. (It'll still be faster than React, anyway!)
    1. tip no 8. API should be explicit!

      Optional props (which are not used) make the component less reusable.

      In my opinion, the API of a component should match strictly the values that are used. If the prop is a large object in which only a subset of of properties are used, then it is better to restrict the API to those set of properties.

    1. I’ve seen some version of this conversation happen more times than I can remember. And someone will always say ‘it’s because you’re too used to thinking in the old way, you just need to start thinking in hooks’.

      But after seeing a lot of really bad hooks code, I’m starting to think it’s not that simple — that there’s something deeper going on.

    1. In most component frameworks, you need to write some code to define your component. With React, the simplest component is an empty function. In other frameworks, you need to import a library and call a special function to define and create your component. With Svelte, you just create a new .svelte file.

      If you compare these two:

      • With React, the simplest component is an empty function.
      • With Svelte, you just create a new .svelte file.

      Creating a new empty function is actually easier/faster than creating and importing a new file. Because you don't have to create a new file just to create a new one-line component. You can create simple helper components within the same file as the main component they help with, and sometimes it is nice to have the flexibility and freedom to compose your files however you want, including the freedom to group multiple closely related components together in the same file.

      In fact one thing I've sometimes found very useful and handy is to be able to define very simple helper components (functions) within the definition of my main component.

      So I would actually put this comparison in the "win" category for React, not Svelte.

    1. The previous example contained a default slot, which renders the direct children of a component. Sometimes you will need more control over placement, such as with this <ContactCard>. In those cases, we can use named slots.

      This is a nicer solution than react children props, which is only clean if you pass in a single child.

      The React children prop is an unregulated wild west where people are free to use the prop almost any way they want (including passing in a function).

      I kind of like how Svelte provides a standard, consistent API, which doesn't have the limitations of React childern.

    1. Q7. What are controlled components?In HTML, form elements such as <input>, <textarea>, and <select> typically maintain their own state and update it based on user input. When a user submits a form the values from the aforementioned elements are sent with the form. With React it works differently. The component containing the form will keep track of the value of the input in it's state and will re-render the component each time the callback function e.g. onChange is fired as the state will be updated. A form element whose value is controlled by React in this way is called a "controlled component".With a controlled component, every state mutation will have an associated handler function. This makes it straightforward to modify or validate user input.

      In classical HTML form components such as <input> or <textarea> maintain their own state, which gets sent somewhere upon submission of the form.

      React keeps track of the form's state inside a component and will re-render the component when the state changes. This can be listened to by subscribing to the onChange callback function.

    2. React creates a virtual DOM. When state changes in a component it firstly runs a “diffing” algorithm, which identifies what has changed in the virtual DOM. The second step is reconciliation, where it updates the DOM with the results of diff.The HTML DOM is always tree-structured — which is allowed by the structure of HTML document. The DOM trees are huge nowadays because of large apps. Since we are more and more pushed towards dynamic web apps (Single Page Applications — SPAs), we need to modify the DOM tree incessantly and a lot. And this is a real performance and development pain.The Virtual DOM is an abstraction of the HTML DOM. It is lightweight and detached from the browser-specific implementation details. It is not invented by React but it uses it and provides it for free. ReactElements lives in the virtual DOM. They make the basic nodes here. Once we defined the elements, ReactElements can be render into the "real" DOM.Whenever a ReactComponent is changing the state, diff algorithm in React runs and identifies what has changed. And then it updates the DOM with the results of diff. The point is - it’s done faster than it would be in the regular DOM.

      React creates a virtual DOM and every time the state of a component changes, it runs a diff algorithm on the virtual DOM. If something needs to be changed, it changes only this part in the HTML DOM. This is faster than the default of updating the entire HTML DOM any time something changes.

    3. The state is a data structure that starts with a default value when a Component mounts. It may be mutated across time, mostly as a result of user events.

      The state is a data structure with a default value at the start which can be mutated based on user events.

    4. Q5. What are the differences between a class component and functional component?Class components allows us to use additional features such as local state and lifecycle hooks. Also, to enable our component to have direct access to our store and thus holds state.When our component just receives props and renders them to the page, this is a ‘stateless component’, for which a pure function can be used. These are also called dumb components or presentational components.

      Functional components cannot hold any state, they are stateless.

  12. Aug 2020
    1. In the two years that I've been working with React professionally, I've never come to a point where I needed to force a re-render. I encourage you to read the article from the beginning if that's what you're here for because usually there's a better way of dealing with React components that aren't updating.
    1. I would shy away from using contexts as your application state. They're intended to be used sparingly. It's likely that some child is changing something in the context and as several items access that context, they're seeing that as a state change they have to care about. I'd highly recommend moving away from contexts as mini-stores and instead focus on how you structure your component tree and the state each one manages.
    1. Merge is a revolutionary technology that lets users import and keep in sync coded React.js components from GIT repositories to the UXPin Editor. Imported components are 100% identical to the components used by developers during the development process. It means that components are going to look, feel and function (interactions, data) just like the real product experienced by the end-users.
  13. Jul 2020
    1. Sure you can hook up different reducers to manage different parts of your application, but the indirection of going through all these action creators and reducers is not optimal.

      On indirection through multiple action creators and reducers for managing different parts of an application

    2. consistently see developers putting all of their state into redux. Not just global application state, but local state as well. This leads to a lot of problems

      global vs local state management. Solutions are not one size fits all.

    3. One of the reasons redux was so successful was the fact that react-redux solved the prop drilling problem. The fact that you could share data across different parts of your tree by simply passing your component into some magical connect function was wonderful.

      Reasons why redux was so successful

    1. It’s like skipping a level. For instance: instead of having to pass, say, a “user” to a Layout and have the Layout pass the “user” to the NavBar, you can create a NavBar (with the user already set) and pass the whole thing into Layout. This can help avoid the “prop drilling” problem where you’ve gotta thread a prop down through multiple layers.
    1. One problem—not a fatal one, but still an issue with any virtual DOM—is that embedding SVGs directly into your app can be a resource hog. No matter how much you compress, no matter how logical and streamlined your components, if you need to load up hundreds of very-complex SVGs, React will need to track all of their nodes, and updating them becomes a chore.
  14. Jun 2020
    1. const httpLink = new HttpLink({ uri: 'https://instagram-clone-3.herokuapp.com/v1/graphql' }); const authLink = setContext((_, { headers }) => { const token = accessToken; if (token) { return { headers: { ...headers, authorization: `Bearer ${token}` } }; } else { return { headers: { ...headers } }; } }); const client = new ApolloClient({ link: authLink.concat(httpLink), cache: new InMemoryCache() });

      concat two link

  15. May 2020