392 Matching Annotations
  1. Jan 2023
  2. Dec 2022
    1. I had been wrapping my components with an improper tag that is, NextJS is not comfortable having a p tag wrapping your divs, sections etc so it will yell "Hydration failed because the initial UI does not match what was rendered on the server". So I solved this problem by examining how my elements were wrapping each other.
    1. ```js import React from "react"; import Dexie from "dexie"; import { useLiveQuery } from "dexie-react-hooks"; import { db } from "./db";

      // // React component // export function OldFriendsList() { const friends = useLiveQuery( () => db.friends .where('age') .above(75) .toArray() );

      if (!friends) return null; // Still loading.

      return

        { friends.map(friend =>
      • {friend.name}, {friend.age}
      • ) }
      ; } ```

    1. Context selectors, however, could be faked with the use of higher-order components and React.memo.
    2. There is no way to prevent a component that uses a portion of Context value from re-rendering, even if the used piece of data hasn’t changed, even with useMemo hook.
    3. ✅ Preventing Context re-renders: Context selectors

    4. If Context manages a few independent data chunks, they can be split into smaller providers under the same provider. That way, only consumers of changed chunk will re-render.
    5. ✅ Preventing Context re-renders: splitting data into chunks

    6. That way, components that use API only won’t re-render when the data changes.
    7. If in Context there is a combination of data and API (getters and setters) they can be split into different Providers under the same component. That way, components that use API only won’t re-render when the data changes.
    8. ✅ Preventing Context re-renders: splitting data and API

    9. If Context Provider is placed not at the very root of the app, and there is a possibility it can re-render itself because of changes in its ancestors, its value should be memoized.
    10. ✅ Preventing Context re-renders: memoizing Provider value

    11. Preventing re-renders caused by Context
    12. ⛔️ Antipattern: random value as key in lists

    13. if the list is static, i.e. elements are not added/removed/inserted/re-ordered
    14. It is okay to use array’s index as key, if the list is static, i.e. elements are not added/removed/inserted/re-ordered.
    15. Value in key should be a string, that is consistent between re-renders for every element in the list.
    16. Important: just providing key attribute will not improve lists' performance. To prevent re-renders of list elements you need to wrap them in React.memo and follow all of its best practices.
    17. Improving re-render performance of lists

    18. the typical use case for useMemo would be to memoize React elements. Usually parts of an existing render tree or results of generated render tree, like a map function that returns new elements
    19. useMemo has its cost (consumes a bit of memory and makes initial render slightly slower)
    20. ✅ useMemo for expensive calculations

    21. If a component uses non-primitive value as a dependency in hooks like useEffect, useMemo, useCallback, it should be memoized.

    22. If a child component is wrapped in React.memo, all props that are not primitive values have to be memoized

    23. ✅ Necessary useMemo/useCallback

      <br/>

    24. ⛔️ Antipattern: unnecessary useMemo/useCallback on props

    25. If a parent component re-renders, it will trigger re-render of a child component regardless of its props.
    26. Memoizing props by themselves will not prevent re-renders of a child component.
    27. React.memo has to be applied to the elements passed as children/props.
    28. ✅ React.memo: components as props or children

      Description

    29. All props that are not primitive values have to be memoized for React.memo to work
    30. ✅ React.memo: component with props

      Description

    31. Wrapping a component in React.memo will stop the downstream chain of re-renders that is triggered somewhere up the render tree, unless this component’s props have changed.
    32. Preventing re-renders with React.memo

      Description

    33. Props are not affected by the state change, so heavy components won’t re-render
    34. encapsulates the state inside a smaller component, and heavy components are passed to it as props
    35. ✅ Preventing re-renders with composition: components as props

      Description

    36. ✅ Preventing re-renders with composition: children as props

      Description

    37. ✅ Preventing re-renders with composition: moving state down

      Description

    38. There is also a big myth: that re-renders happen when the component’s props change. By itself, it’s not true (see the explanation below).
    39. hooks changes
    40. context changes
    41. parent (or children) re-renders
    42. state changes
    43. There are four reasons why a component would re-render itself:
  3. Nov 2022
    1. ReactJS vs React Native: A Comparison Guide for 2023

      React Native vs ReactJS have become two of the most popular web development technologies in the world. The main difference between ReactJS and React native is that ReactJS is JavaScript while ReactJS native is mobile app development framework. Let’s take a closer look at the advantages and disadvantages of ReactJS vs React native. https://bit.ly/3fo6Lwl

  4. Oct 2022
  5. Sep 2022
    1. Sometimes, Create React App will produce an error when you try to create a new application using npx or npm init.

      Create React App no longer support global installation This is how to fix the issue

    1. ```js import { useState } from 'react';

      /* * @return {Function} getterSetter / export function useStateFunction(initialValue) { const [state, setState] = useState(initialValue);

      return function(...args) {
          if (args.length === 0) {
              return state;
          }
          return setState(...args);
      };
      

      } ```

    1. ```js function App() { const buttonRef = useRef(null); const hookValue = useMyHook(buttonRef.current); const [forceUpdate, setForceUpdate] = useState(false);

      return ( <div> <button onClick={() => setForceUpdate(prevState => !prevState)}> Update Component </button> <button ref={buttonRef}>Update Hook</button> {"This is hook returned value: " + hookValue} </div> ); } ```

      ```js import { useEffect, useState } from "react";

      function useMyHook(element) { const [myHookState, setMyHookState] = useState(0);

      console.log("Inside useMyhook..."); console.log("This is the element received: " + element);

      useEffect(() => { console.log("Inside useMyhook useEffect...");

      function onClick() {
        setMyHookState(prevState => prevState + 1);
      }
      
      if (element !== null) {
        element.addEventListener("click", onClick);
      }
      return () => {
        console.log("Inside useMyhook useEffect return...");
        if (element !== null) {
          element.removeEventListener("click", onClick);
        }
      };
      

      });

      return myHookState; }

      export default useMyHook; ```

  6. Aug 2022
    1. And in our case, we want it to keep track of our storage object. So let's also create a usePeristentContext hook.

      ```js import { useMutation, useQuery, useQueryClient } from 'react-query';

      export default function usePersistentContext(key) { const queryClient = useQueryClient();

      const { data } = useQuery(key, () => localStorage.getItem(key));

      const { mutateAsync: setValue } = useMutation( (value) => localStorage.setItem(key, value), { onMutate: (mutatedData) => { const current = data; queryClient.setQueryData(key, mutatedData); return current; }, onError: (_, __, rollback) => { queryClient.setQueryData(key, rollback); }, } );

      return [data, setValue]; } ```

      js function SetContext() { const [value, setValue] = usePersistentContext('item_context'); return ( <button onClick={() => setValue(value === 'on' ? 'off' : 'on')}> Click me {value} </button> ); }

    1. The clientHeight property returns the inner height of an element in pixels. The property includes padding but excludes borders, margins and horizontal scrollbars.Alternatively, you can use the offsetHeight property, which returns the height of the element in pixels, including vertical padding and borders.

      ```js useEffect(() => { setDivHeight(ref.current.offsetHeight); console.log('height: ', ref.current.offsetHeight);

      console.log('width: ', ref.current.offsetWidth); }, []); ```

    1. ```js export function Tweet({ tweetID, }) { const tweetRef = useRef(null); const [isLoading, setIsLoading] = useState(true);

      useEffect(() => { const tweetEl = tweetRef?.current if (window.twttr && tweetEl) (async() => { await window.twttr.ready(); await window.twttr.widgets.createTweet( tweetID, tweetEl, { align: 'center', conversation: 'none', dnt: true, } ); setIsLoading(false); console.log('Tweet loaded') })(); return () => { tweetEl?.remove(); } }, [tweetID, tweetRef]);

      return ( <div ref={tweetRef} className="w-full bg-gray-100 h-fit animate-fadeIn" id={tweetID}> {isLoading &&

      🐦

      } </div> ); }; ```

  7. Jul 2022
  8. github.com