Friday, February 9, 2024

Advanced React Hacks 4/10 - Prevent Rerenders

Advanced React Hacks 4/10 - Prevent Rerenders


Very obvious when you see the answer (and actually documented on react.dev, link later) but still worth mentioning for posterity.

You don't want to render too much, because one point of React is that it minimises the amount of rerenders on a screen (or is supposed to)


How do most working React developers see this? With the "highlight updates" tool of course


But, it is worth mentioning (in case it happens again, and for a lesson) that in 2019 with React Developer Tools v4, this killer feature was removed


To the React Team's credit, they restored "Highlight Updates" quickly

Anyway how do you prevent re-rendering? It's actually easy

Once the component has been initially rendered, you can trigger further renders by updating its state with the set function. Updating your component’s state automatically queues a render. (You can imagine these as a restaurant guest ordering tea, dessert, and all sorts of things after putting in their first order, depending on the state of their thirst or hunger.) React.Dev "Managing State"

If you see too much of your screen rendering making it slow when taking actions (like clicking) break it down



Make more components... obvious, but worth mentioning the obvious

Until next time...


Saturday, February 3, 2024

Advanced React Hacks 3/10 - Dynamic GraphQL

Advanced React Hacks 3/10 - Dynamic GraphQL

Eventually you will reach a point in your career where you need or want to make dynamic GraphQL queries


At first it will seem "advanced" especially when looking at Google or Stack Overflow answers

You probably are used to static queries strongly typed from a schema.graphql with autocomplete in VSCode

How the hell can that change or be data driven?



Well the answer is in the specification

Typically validation is performed in the context of a request immediately before execution, however a GraphQL service may execute a request without immediately validating it if that exact same request is known to have been validated before. A GraphQL service should only execute requests which at some point were known to be free of any validation errors, and have since not changed.

For example: the request may be validated during development, provided it does not later change, or a service may validate a request once and memoize the result to avoid validating the same request again in the future.

Request may be validated during development => request may be validated during runtime => request may change!

For example with graphql-tag

GraphQL strings are the right way to write queries in your code, because they can be statically analyzed using tools like eslint-plugin-graphql. However, strings are inconvenient to manipulate, if you are trying to do things like add extra fields, merge multiple queries together, or other interesting stuff.

That's where this package comes in - it lets you write your queries with ES2015 template literals and compile them into an AST with the gql tag.

With string interpolation, "dynamic GraphQL" is actually trivial! Just build the string! (And this is JavaScript not Java so you don't need a StringBuilder!)

So,

a) RTFM (in this case the specification!)

b) Never trust the "right way"

c) Look for an existing solution

d) Probably more things I haven't thought of...

Back to basics!


Hope this helps someone!

Saturday, January 27, 2024

Advanced React Hacks 2/10 - Dynamic JSX

 Advanced React Hacks 2/10 - Dynamic JSX

What if you want a data driven application that renders JSON (not HTML obviously, always BBCode!) as JSX?



One way is React.Children


Instead do this,

export const Component = ({ children }: { children: ReactNode }) => {
  const isArray = Array.isArray(children);
  return (
    <>
      {!isArray && children}
      {isArray &&
        children.map((child, index) => {
          return <div key={index}>{child}</div>; // do stuff to the child here
        })}
    </>
  );
};

Now you can use it

import { Component } from "./Component";

export default function App() {
  return (
    <div>
      <Component>test</Component>
      <Component>
        <div>test2</div>
        <div>test3</div>
      </Component>
      <Component>
        <div>test4</div>
        <div>test5</div>
      </Component>
    </div>
  );
}

(Wow pasting from CodeSandbox worked!)

https://codesandbox.io/p/sandbox/cranky-haslett-749y8y

Hope this helps someone!

Sunday, January 21, 2024

Advanced React Hacks 1/10 - Conditional Hooks

Advanced React Hacks 1/10 - Conditional Hooks

 According to react.dev "Rules of Hooks" you cannot call hooks inside a condition

https://react.dev/warnings/invalid-hook-call-warning#breaking-rules-of-hooks

But what if you want it?


Use components!

export const ParentComponent = ({ component }: ParentComponentProps) => {

  /* derive condition here */
  // const condition = false;
  const condition = true;

  /* derive property here */
  // cont property = 0;
  // ...

  return (<>
    {
      condition && <HookComponent hookProperty={property} />
    }
  </>);
}

export const HookComponent = ({ hookProperty }: ChildComponentProps) => {
  useCustomHook(hookProperty); // could be anything!
  return <></>; // yes, components can render nothing
}

With great power comes great responsibility!

Hope this helps! More next time...