React - atabegruslan/Notes GitHub Wiki
- https://codeburst.io/setting-up-a-react-project-from-scratch-d62f38ab6d97
- https://www.codementor.io/@tamizhvendan/beginner-guide-setup-reactjs-environment-npm-babel-6-
- https://reactjs.org/docs/create-a-new-react-app.html
- https://www.digitalocean.com/community/tutorials/how-to-set-up-a-react-project-with-create-react-app
- From scratch:
- *Need update, nowadays we use Vite. RCA is deprecated and no longer maintained. So do
npm create vite@latest
Component = Blueprint (like a Class) Component-Instance = Occurrence of a Component. Only for Class Components React-Element = A plain immutable JS object describing the instance/DOM-Element
- https://gist.github.com/atabegruslan/7ce2c8a0593ea34569085486d809c5a2 (Read!)
- https://www.freecodecamp.org/news/react-interview-question-what-gets-rendered-in-the-browser-a-component-or-an-element-1b3eac777c85
- https://www.geeksforgeeks.org/differences-between-functional-components-and-class-components-in-react/
- https://www.twilio.com/blog/react-choose-functional-components
- https://stackoverflow.com/questions/36097965/when-to-use-es6-class-based-react-components-vs-functional-es6-react-components/36137801#36137801
So functional components are simpler and seems to be the way of the future. They simply take props and render. Use class components only when you want more complex state management abilities.
For conversion between class <-> functional components, here's how: https://jsfiddle.net/atabegaslan/uspx4mLy/
-
https://viblo.asia/p/component-patterns-in-react-6J3ZgjvgKmB
-
https://reactjs.org/blog/2015/12/18/react-components-elements-and-instances.html
-
https://overreacted.io/how-are-function-components-different-from-classes/
-
https://dev.to/prabangkoro/react-method-component-vs-class-component-56fj
-
https://reactkungfu.com/2015/10/the-difference-between-virtual-dom-and-dom/
- https://www.javatpoint.com/react-version
- https://stackoverflow.com/questions/33526493/react-createclass-vs-extends-component
- https://ultimatecourses.com/blog/react-create-class-versus-component
- https://medium.com/hackernoon/replacing-componentwillreceiveprops-with-getderivedstatefromprops-c3956f7ce607
- v17 -> v18: https://reactjs.org/blog/2022/03/08/react-18-upgrade-guide.html
- v18 -> v17: https://dev.to/lowla/create-react-app-with-a-previous-version-of-react-4g03
As of 2023/2024: Use Vite, dont use RCA, because RCA havent been maintained in ages.
- https://www.w3schools.com/REACT/react_lifecycle.asp
- https://www.freecodecamp.org/news/how-to-understand-a-components-lifecycle-methods-in-reactjs-e1a609840630/
- https://reactjs.org/docs/hooks-overview.html
- https://www.youtube.com/watch?v=TNhaISOUy6Q Good
- https://www.youtube.com/watch?v=LlvBzyy-558
- https://reactjs.org/docs/hooks-reference.html ( https://legacy.reactjs.org/docs/hooks-reference.html ) Old
- https://www.youtube.com/watch?v=LOH1l-MP_9k Good
- React 19 hooks: https://www.youtube.com/watch?v=2NPIYnY3ilo
- https://www.youtube.com/playlist?list=PLZlA0Gpn_vH8EtggFGERCwMY5u5hOjf-h Good
- https://www.youtube.com/playlist?list=PL_-VfJajZj0W8-gf0g3YCCyFh-pVFMOgy
- https://github.com/mobxjs/mobx-react/issues/447
- https://stackoverflow.com/questions/53464595/how-to-use-componentwillmount-in-react-hooks
Only use state if:
- Cannot be computed on each render, and,
- No place else (eg browser storage) have that state, and,
- Does not need to be rendered
- Value isn't a derived value. (Derived value is eg: Formatted date from date)
Common mistakes:
So do this instead:
const [muted, setMuted] = useState(false);
const clickHandlerFunction = () => {
console.log('muted before', muted);
setMuted(!muted);
}
useEffect(() => {
console.log('muted after', muted);
}, [muted])
Don't overuse this. Stay away from useEffect
by:
- Derive value in each render
- Respond to events with event handlers whenever you can
- Fetch with a
react-query
or one of those other libraries specifically for fetching.
Common pitfalls:
Make it run only once (strict mode)
- https://www.youtube.com/watch?v=81faZzp18NM
- https://stackoverflow.com/a/60619061
- https://www.geeksforgeeks.org/how-to-fix-react-useeffect-running-twice
- https://www.reddit.com/r/reactjs/comments/f647zr/calling_a_debounced_function_from_useeffect_what/?rdt=49933
- https://stackoverflow.com/a/61887599
- https://www.geeksforgeeks.org/lodash-_-debounce-method/
Cache the result of expensive computations and won't recompute unless change
https://www.youtube.com/watch?v=THL1OPn72vo
Cache functions
https://www.youtube.com/watch?v=IL82CzlaCys
Note: {// to complete}
Refs |
`useRef` hook
https://www.youtube.com/watch?v=t2ypzz6gJm0&list=PLZlA0Gpn_vH8EtggFGERCwMY5u5hOjf-h |
 | ``` // to complete ``` |
forwardRef
Passing ref to child
https://www.youtube.com/watch?v=RLWniwmfdq4
To let parent control a functionality of child
The related Provider Pattern example: https://github.com/Ruslan-Aliyev/ReactJS_ProviderPattern
Context API
For class components |
`useContext` hook
For function components https://www.youtube.com/watch?v=5LrDIWkK_Bc&list=PLZlA0Gpn_vH8EtggFGERCwMY5u5hOjf-h |
//==App.js======================================== import React from 'react'; import PageContextProvider from './PageContextProvider'; import Header from './Header'; function App() { return ( <div className="App"> <PageContextProvider> <Header /> </PageContextProvider> </div> ); } export default App; //==PageContextProvider.js========================= import React, { useState, useEffect, createContext } from 'react'; export const PageContext = createContext(); const PageContextProvider = (props) => { const [user, setUser] = useState({ 'name': 'harry potter' }); return ( <PageContext.Provider value={{ user: user }}> {props.children} </PageContext.Provider> ); } export default PageContextProvider; //==Header.js===================================== import React, { Component } from 'react'; import { PageContext } from './PageContextProvider'; class Header extends Component { render() { return ( <PageContext.Consumer> {user => { return <div className="header">{user.name}</div> }} </PageContext.Consumer> ); } } export default Header; |
//==App.js======================================== import React from 'react'; import PageContextProvider from './PageContextProvider'; import Header from './Header'; function App() { return ( <div className="App"> <PageContextProvider> <Header /> </PageContextProvider> </div> ); } export default App; //==PageContextProvider.js========================= import React, { useState, useEffect, createContext } from 'react'; export const PageContext = createContext(); const PageContextProvider = (props) => { const [user, setUser] = useState({ 'name': 'harry potter' }); return ( <PageContext.Provider value={{ user: user }}> {props.children} </PageContext.Provider> ); } export default PageContextProvider; //==Header.js===================================== import React, { useContext } from 'react'; import { PageContext } from './PageContextProvider'; const Header = () => { const { user } = useContext(PageContext); return ( <div className="header">{user.name}</div> ); } export default Header; |
So in summary:
https://www.w3schools.com/react/react_customhooks.asp
useFetch.js
import { useState, useEffect } from "react";
const useFetch = (url) => {
const [data, setData] = useState(null);
useEffect(() => {
fetch(url)
.then((res) => res.json())
.then((data) => setData(data));
}, [url]);
useDebugValue(data ?? 'loading...'); // useDebugValue adds a label to this custom hook, which can be seen in the React dev tools console
return [data];
};
export default useFetch;
index.js
import ReactDOM from "react-dom/client";
import useFetch from "./useFetch";
const Home = () => {
const [data] = useFetch("https://jsonplaceholder.typicode.com/todos");
- Tanstack
useQuery
: https://www.youtube.com/watch?v=AlkDbnbv7dk
https://www.npmjs.com/package/react-query has now became https://tanstack.com/query/latest/docs/framework/react/quick-start
Another example of tanstack/react-query
& Form Submit: https://gist.github.com/atabegruslan/78b782f3cd39bcad6f8caa7dda32fd8f
-
The new React 19's
use
hook
usePathname()
returns the same thing as window.location.pathname
Example: To prevent the form's submit button being repeatedly pressed during submission
https://react.dev/reference/react/useActionState
Example: After you send a message on a chat messenger. It will tell show you that the message has already been sent (for good user experience). Then when the message has actually been delivered, then it updates the message's status to 'delivered'.
Class component | Function component |
class ErrorBoundary extends React.Component { constructor(props) { super(props); state = { hasError: false }; } static getDerivedStateFromError(error) { return { hasError: true }; } componentDidCatch(error, errorInfo) { errorService.log({ error, errorInfo }); } render() { if (this.state.hasError) { return <h1>Oops, we done goofed up</h1>; } return this.props.children; } } ReactDOM.render( <ErrorBoundary> {/* This App have problems */} <App /> </ErrorBoundary>, document.getElementById('root') ) |
import {ErrorBoundary} from 'react-error-boundary' function ErrorFallback({error, resetErrorBoundary}) { return ( <div role="alert"> <p>Something went wrong:</p> <pre>{error.message}</pre> <button onClick={resetErrorBoundary}>Try again</button> </div> ) } const ui = ( <ErrorBoundary FallbackComponent={ErrorFallback} onReset={() => { // reset the state of your app // so the error doesn't happen again }}> <ComponentThatMayError /> </ErrorBoundary> ) |
- https://www.digitalocean.com/community/tutorials/react-error-boundaries
- https://www.youtube.com/watch?v=ieOhZJbLptc&list=RDCMUCCTVrRB5KpIiK6V2GGVsR1Q
- Before understanding code split, read Lazy load first: https://www.youtube.com/watch?v=tV9gvls8IP8
- https://www.youtube.com/watch?v=Ef3nvKLS4no
- https://reactjs.org/docs/code-splitting.html
- https://github.com/Ruslan-Aliyev/React-Routing#code-splitting
- https://www.youtube.com/watch?v=B36pSPMSzZI
- https://www.youtube.com/watch?v=nks5rQEZsQg
- Time Travel Debugging: https://medium0.com/the-web-tub/time-travel-in-react-redux-apps-using-the-redux-devtools-5e94eba5e7c0
- https://www.toptal.com/react/react-context-api , https://www.youtube.com/watch?v=XkBB3pPY3t8&list=PL4cUxeGkcC9hNokByJilPg5g9m2APUePI&index=2
- https://scotch.io/courses/5-essential-react-concepts-to-know-before-learning-redux/presentational-and-container-component-pattern-in-react
- https://www.youtube.com/watch?v=76FRrbY18Bs
- https://www.newline.co/fullstack-react/30-days-of-react/day-18/
- https://www.imaginea.com/redux-vs-mobx-what-you-need-to-know/
- https://www.educba.com/redux-alternatives/
- https://www.valentinog.com/blog/redux/
- https://stackoverflow.com/questions/33526596/what-are-the-advantages-of-react-and-flux-apart-from-virtual-dom-concept
- https://www.newline.co/fullstack-react/articles/redux-with-mark-erikson/
- https://www.clariontech.com/blog/mvc-vs-flux-vs-redux-the-real-differences
- https://yourstory.com/mystory/flux-vs-redux
- https://dev.to/rosyshrestha/build-your-first-app-with-mobx-and-react-4896
- https://www.npmjs.com/package/mobx-react
- Alternatives to Redux
- MobX, eg demo https://github.com/atabegruslan/React-MobX
- Apollo Client & GraphQL
- RxJS, good tutorial: https://www.youtube.com/watch?v=2LCo926NFLI
- ( Concept of push & pull: https://github.com/atabegruslan/Notes/wiki/JS-Async#idea-of-pull-vs-push )
- https://redux.js.org/tutorials/fundamentals/part-4-store#middleware
- https://github.com/reduxjs/redux-thunk
- https://redux-saga.js.org/
- https://github.com/reactjs/react-tutorial
- https://github.com/learncodeacademy/react-js-tutorials
- https://github.com/meteor/simple-todos-react
- https://jscomplete.com/learn/react-beyond-basics/react-fundamentals
-
https://dev.to/nburgess/creating-a-react-app-with-react-router-and-an-express-backend-33l3
-
Add one more row: https://github.com/Ruslan-Aliyev/React-AddRows
- https://dzone.com/articles/top-10-most-common-commands-for-beginners
- https://stackoverflow.com/questions/36994564/how-can-one-tell-the-version-of-react-running-at-runtime-in-the-browser
- To stop this server process and free up the port, press Cntr + C, or find and delete the process:
- https://medium.com/dailyjs/what-is-actually-css-in-js-f2f529a2757
- https://medium.com/@dmitrynozhenko/9-ways-to-implement-css-in-react-js-ccea4d543aa3
- https://stevenwestmoreland.com/2018/01/how-to-include-bootstrap-in-your-project-with-webpack.html
- https://www.upbeatcode.com/react/css-scoping-in-react-everything-you-need-to-know/
- https://stackoverflow.com/questions/47090574/how-to-make-react-css-import-component-scoped/47090832#47090832
- https://dev.to/alserembani/react-vs-vue-how-about-some-style-1ofi
- Comparison to Vue's
<style scoped
: https://vue-loader.vuejs.org/guide/scoped-css.html
- https://github.com/atabegruslan/Notes/wiki/Backend-JS#webpack
- https://stackoverflow.com/questions/43002099/rules-vs-loaders-in-webpack-whats-the-difference
- https://webpack.js.org/configuration/
- https://stackoverflow.com/questions/50591374/mern-stack-express-and-react-on-same-port
- https://medium.com/bb-tutorials-and-thoughts/react-how-to-proxy-to-backend-server-5588a9e0347
- https://stackoverflow.com/questions/44365577/proxy-in-package-json-not-affecting-fetch-request webpack
- https://stackoverflow.com/questions/51968782/proxy-included-in-package-json-not-working/52817464#52817464 Differently in Vue
- https://stackoverflow.com/questions/41889789/how-to-refresh-list-after-successfully-created-post-in-react-redux-form
- https://stackoverflow.com/questions/42985478/react-and-redux-redirect-after-action/42985875
- https://www.pluralsight.com/guides/how-to-transition-to-another-route-on-successful-async-redux-action Good
- https://stackoverflow.com/questions/35706835/react-router-redirect-after-action-redux
- https://forum.freecodecamp.org/t/how-can-i-redirect-after-successful-post-react-redux-node-express/259863/5
- https://medium.com/@panktip85/redirect-with-react-redux-afeda0bd12fb
- https://www.xspdf.com/resolution/51822219.html Good
- https://www.tutorialspoint.com/reactjs/reactjs_router.htm
- https://www.sitepoint.com/react-router-complete-guide/ Good
- https://reactrouter.com/web/api/Redirect
- https://stackoverflow.com/questions/46820682/how-do-i-reload-a-page-with-react-router Good
- https://www.npmjs.com/package/react-router
npm install [package_name] --save is used to save the package required for the application to run.
npm install [package_name] --save-dev is used to save the package for development purpose. Example: unit tests, minification..
Short Explanation https://stackoverflow.com/questions/22891211/what-is-the-difference-between-save-and-save-dev
Long Explanation https://stackoverflow.com/questions/33504641/whats-the-difference-between-save-and-save-dev-in-npm-install/33507291
Note 1: https://www.youtube.com/watch?v=w5TupxbnnrM&t=261s to 426s
Note 2: https://github.com/Microsoft/types-publisher/issues/81#issuecomment-234051338