React (JavaScript library)

From David's Wiki
Revision as of 02:52, 8 February 2023 by David (talk | contribs)
\( \newcommand{\P}[]{\unicode{xB6}} \newcommand{\AA}[]{\unicode{x212B}} \newcommand{\empty}[]{\emptyset} \newcommand{\O}[]{\emptyset} \newcommand{\Alpha}[]{Α} \newcommand{\Beta}[]{Β} \newcommand{\Epsilon}[]{Ε} \newcommand{\Iota}[]{Ι} \newcommand{\Kappa}[]{Κ} \newcommand{\Rho}[]{Ρ} \newcommand{\Tau}[]{Τ} \newcommand{\Zeta}[]{Ζ} \newcommand{\Mu}[]{\unicode{x039C}} \newcommand{\Chi}[]{Χ} \newcommand{\Eta}[]{\unicode{x0397}} \newcommand{\Nu}[]{\unicode{x039D}} \newcommand{\Omicron}[]{\unicode{x039F}} \DeclareMathOperator{\sgn}{sgn} \def\oiint{\mathop{\vcenter{\mathchoice{\huge\unicode{x222F}\,}{\unicode{x222F}}{\unicode{x222F}}{\unicode{x222F}}}\,}\nolimits} \def\oiiint{\mathop{\vcenter{\mathchoice{\huge\unicode{x2230}\,}{\unicode{x2230}}{\unicode{x2230}}{\unicode{x2230}}}\,}\nolimits} \)

Components

React has two types of components: class components (those which extend React.Component) and function components. Function components are lighter weight than class components and should be preferred for new code.

Function components

State

https://beta.reactjs.org/learn/managing-state State can be managed in several ways:

  • useState allows you to define a state variable, similar to a class property, which will trigger a rerender.
  • useReducer allows you to refractor state manipulation to a separate reducer function outside of your component.
  • useEffect allows you to setup and remove listeners. These always run on the client in SSR variants of React.
  • Contexts
  • useRef returns a reference to an object with a current parameter which allows you to have state without rerendering.

Every time any properties or state changes, your function component will be rerendered. Therefore, you cannot rely on local variables to hold their state. Additionally, you must call useState identically across renders (i.e. not conditionally), ideally near the top of your function.

Note that the state of the function is tied to their position in the React virtual dom. A single component rendered multiple times will have different state.


Frameworks

Next.js

Next.js allows you to use React with server-side rendering.

Resources