This is a collection of code snippets to show the concepts of React with TypeScript in a pragmatic way.
All code snippets are available in kind of Components, Tests, (Utility) Functions, etc.
The goal is to show replicating and adaptable concepts and techniques.
Thereby, the comprehensibility and self-explanation within the code is in the foreground. It will make it possible, even for beginners, to find inspiration.
So, you need to look at the output on the console along with the code.
In other words: Always have your developer tools open π
It's important to note that I am showing some ways and approaches here. There is no generally right or wrong way (apart from "real" mistakes π).
Yes, π there's an executable App (at Codesandbox), that can also run locally on your machine (see below).
Keep in mind: The focus is still on the code and tests and not on a fancy UI/UX with enterprise-relevant features π
This repository is a start and should grow πͺ.
Feel free to post your ideas or questions in the form of issues. Often a single sentence is enough (e.g., the title of an issue).
I am happy about every pull request (PR) from you too. Regardless if it adds concepts, corrects errors, simplifies things or describes things betterβwhatever comes to your mind π₯³.
The steps to follow to contribute to this project you can find here.
| π§ Please be awareβ¦ |
|---|
| Everything in this repository is a work in progress. It's constantly changing and improving. So, there is never a finished version π€·. |
# Check out the main-branch of this repository and switch into this directory
git clone git@github.com:tscharke/mentor-playground.git && cd "$(basename "$_" .git)"
# Install all dependencies
yarn install
# Start API and frontend together
yarn run start
# (Optional) Start the BookMonkey API in a separate terminal
# yarn run start:api
# (Optional) Start the development-server in a separate terminal
# yarn run start:serverπ€© After starting the development-server, the application is showing up under http://localhost:3000.
The BookMonkey API is installed locally via package.json and starts on http://localhost:4730.
Basic examples of React components to get started:
FirstComponent.tsxβ a minimal functional componentSecondComponent.tsxβ a slightly more advanced componentPassProperties.tsxβ demonstrates how to pass props to components
UseState.tsxβ basic state management withuseStateComponentWithState.tsxβ a component that holds and updates local stateComponentWithStateAndChildren.tsxβ state combined with child components
ComponentUseEffectHook.tsxβ side effects and the lifecycle of a functional component
A useReducer works like useState, but uses the Reducer concept from Redux to manage state changes.
A Reducer is a plain TypeScript function (state, action) => state that decides β based on the dispatched Action β whether and how the state changes.
UseReducerComponent.tsxβ component that uses theuseReducer-Hook; renders a task-list with buttons to change each task's progress (Open β In progress β Done)reducer.tsβ the Reducer function itselfreducer.test.tsβ tests for the Reducerinterfaces.tsβ shared type definitions
UseContext1.tsx,UseContext2.tsx,UseContext3.tsxβ three progressive examples showing how to create and consume a React Context
CustomHook.tsxβ a customuseFetchDataFromAPIhook that encapsulates data-fetching logic
UseRefHook.tsxβ accessing and manipulating DOM elements withuseRef
UseMemo.tsxβ memoising expensive computations to avoid unnecessary recalculations
UseCallback.tsxβ stabilising function references to prevent unnecessary re-renders
UseExternalStoreComponent.tsxβ subscribing to an external store in a concurrent-safe way
- Examples of styling React components using CSS Modules and Styled Components
Controlled.tsxβ controlled form inputs (React manages the value)Uncontrolled.tsxβ uncontrolled form inputs (DOM manages the value viauseRef)
ErrorBoundary.tsxβ class-based Error Boundary to catch render errorsErrorHandlingDemo.tsxβ demonstrates how an Error Boundary wraps componentsFallback.tsxβ the fallback UI shown when an error is caught
SuspenseDemo.tsxβ lazy-loading components withReact.SuspenseandReact.lazyUserList.tsxβ data-fetching with Suspense using a custom resource helper
- A small book-management feature that connects to the local BookMonkey API (
http://localhost:4730) - Demonstrates Redux-style state management:
actions.ts,reducer.ts,reduxStore.ts BookList.tsx&BookItem.tsxβ list and detail componentshooks.tsβ custom hooks to interact with the store
Demonstrates how to offload work to a background thread using the Web Workers API:
WebWorker.tsxβ component that spawns a Web Worker, listens to its reply via anEvent, and displays the steps to followworker.tsβ the actual worker script running in the backgrounduseChangeBackgroundColor.tsβ custom hook that sets a random background colour on a referenced HTML elementuseChangeBackgroundColor.test.tsβ tests for the custom hookExplanation.tsxβ component describing the steps to follow
Explains the Iterator Protocol and Generators in depth β with code examples and test suites:
- Iterators: Any object that wants to be iterable must implement
[Symbol.iterator](), which returns anext()function yielding{ value, done }objects. Built-in types likeArrayandStringalready include this β sofor-ofworks on them out of the box.iterators.test.tsβ shows how to use iterators, what happens without one, and how to implement your own
- Generators: Functions declared with
function*that automatically produce an iterator.generators.test.tsβ coversfunction*syntax, generator implementation, and the connection to iterators
A collection of pragmatic TypeScript/JavaScript snippets β most output to the browser console:
shallowCopy.tsβ object spread creates only a shallow clone; nested objects still share referencesscope.tsβvarfunction scope and the classicloop + setTimeoutclosure pitfallpromises.tsβ comparesPromise.all,Promise.race, andPromise.allSettledfunctions.tsβ declaration vs expression vs arrow functions; static vs instance-level propertiesreducer.tsβ typedArray.prototype.reducewith inline and external reducer functionsasyncReducer.tsβ async reduction over fetched data and why the accumulator becomes aPromisemodules.tsβ module patterns: IIFE, CommonJS, AMD, UMD, native modules, and closure-based encapsulationinterfacesAndUtilityTypes.tsβ index signatures andRecordto model constrained and dynamic object shapesusageOfInterfaces.tsxβ separating public/private props to model component API boundariesfactorial.test.tsβ iterative vs recursive factorial including boundary and error casesleftPadding.test.tsβ numeric left-padding across positive/negative integers, floats, and signed zeroinvertTree.test.tsβ recursive inversion of a binary treedecorator.test.tsβ TC39 Stage 3 decorators (class, property, method); execution timing of each decorator type
- Examples of React's experimental
use-Hook for reading resources (Promises, Context) directly inside render
I love if you want to contribute to this project. To do so, please follow the steps described here - thank you very much β€οΈπ
My thanks for the photo displayed on social media goes to: Desola Lanre-Ologun
Nik Sumeiko π§βπ« |