React (JavaScript library): Difference between revisions
| Line 2: | Line 2: | ||
==Components== | ==Components== | ||
React has two types of components: class components (those which extend React.Component) and function components. | React has two types of components: class components (those which extend React.Component) and function components. | ||
Function components are lighter weight | Function components are lighter weight and should be preferred for new code. | ||
===Function components=== | ===Function components=== | ||
Revision as of 03:52, 8 February 2023
Components
React has two types of components: class components (those which extend React.Component) and function components. Function components are lighter weight and should be preferred for new code.
Function components
State
https://beta.reactjs.org/learn/managing-state State can be managed in several ways:
useStateallows you to define a state variable, similar to a class property, which will trigger a rerender.useReducerallows you to refractor state manipulation to a separate reducer function outside of your component.useEffectallows you to setup and remove listeners. These always run on the client in SSR variants of React.- Contexts
useRefreturns a reference to an object with acurrentparameter 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.