React Notes: Revisisiting Key React JS Concepts
I have learnt React briefly a couple of months ago. It’s a good idea to reinforce the fundamentals by revisiting some of the key concepts of this library before diving in deeper.
Somehow, learning python
for the pass few months makes me more confident and easier to understand the concepts, syntax as well as the logic.
Gratitudes to Cem Eygi for brilliant posts so I can understand the concept and mechanism of React JS.
Introduction to React JS
-
React is a library not a framework
- frameworks are complete packages, less flexible
- projects does not depend on libraries
-
DOM (Document Object Model)
- document: page itself
- objects: HTML tags
- model: a tree structure
-
React’s Virtual DOM:
- is a copy of the original DOOM
- only changes parts of the page where changes are made –> much faster
- instead of traditionally rendering whole page when every single change was made
-
React DOM compares the element and its children to the previous one, and only applies the DOM updates necessary to bring the DOM to the desired state - official doc
- an example of rendering command:
ReactDOM.render(element, document.getElementById('root));
-
JSX (JavaScript XML) - a syntax extension to JavaScript:
- ‘Tis not JS nor HTML
const element = <h1>Hello!</h1>;
- is used to write HTML in JavaScript
- will be translated by
Babel
to normal JavaScript
some rules:
- ‘class’ => ‘className’
- ‘tabindex’ => ‘tabIndex’
- only return a SINGLE HTML tag
- ‘Tis not JS nor HTML
-
Installation:
- install
Node.js
, here:an asynchronous event-driven JavaScript runtime, Node.js is designed to build scalable network applications… about Node.js
$ npx create-react-app my-app
to create your app$ cd my-app
go into the project folder$ npm start
to start serving locally
- install
Functional and Class Components
Components are reusable parts of the code. You can reuse the same code to generate multiple parts of the website with the same charactoristics for example. It’s a bit like CBV in Django, or class in Python. Except in the world of React, the whole website is generated by numerous components. That’s probably why it can rerender only parts of the DOM instead of rerendering the whole page causing bad UX.
Basically, you don’t have to use Class Components to handle complex logic now. After the introduction of React Hooks
, functional components can do complex state handling as well. However, it’s not mandatory to change old Class compo to func compo. And the Class components will be further supported as well.
The mechanism in React is not terribly difficult. EveryComponent
(capitalized camelCasely named) is defined/lives in their own file and has their own css file, returns/renders an HTML element in JSX syntax. When you need to use them, import them and call them in the root file(app.js
). And the components are called in HTML tags: <EveryComponent />
. And they HAVE TO be closed.
Two equivalent components in function and class
function Welcome(props) {
return <h1>Hello, {props.name}</h1>;
}
class Welcome extends React.Component {
render() {
return <h1>Hello, {this.props.name}</h1>;
}
}
Note:
Note: Always start component names with a capital letter.
React treats components starting with lowercase letters as DOM tags. For example,<div />
represents an HTML div tag, butrepresents a component and requires Welcome
to be in scope.
To learn more about the reasoning behind this convention, please read JSX In Depth.
props, i.e. prpperties
FACTS:
- props are objects
- props are immutable
- props can ONLY be passed from a parent to a child: a uni-directional flow
- props are passed in like this
<ChildCompo text={"a string"} />
METAPHORS:
- props are like
dict
objects in python, if they are passed in like this<ChildCompo text={"a string"} />
- a key/value pair, if youconsole.log(props)
you’ll getObject { text: "a string"}
- it’s like
context
in django, onlytext
doesn’t have to be in quotes, it’s passed inhtml templates
to render, in React world, it’s the child component to render itself with the data received, i.e. the props - it’s just like the
context
being accessed intemplates
: you can access the value withdot notation
in interpolation{}
:{ props.text }
, just like django templates in ``
THOUGHTS:
I remember reading more than one post recommending to stick with a language and to code in projects if you want to learn it fast. I think the reason for that is, for a beginner, the only way to truly enter the programming world is to develope a group of nerves which are tuned to respond and process the specific logic which the programmer and programming languages share for problem solving. And you will discover the similarities amongst the different languages and frameworks. Once you get a hang of it, it does get easier so they say. Fingers crossed.
state
FACTS:
- a state is for a component ONLY (private), it can NOT be passed to others, however, props CAN
- state lives/is defined in
constructor()
method (if it’s a class component):constructor() { this.state = { id: 1, name: "test" }; }
- and later can be accessed
{this.state.id}
or{this.state.name}
- a
constructor()
is like__init__()
method in python class, which is to initiate the class based object
- and later can be accessed
- state can be changed unlike props, but it can only be changed using
setState()
method and never be reasigned with=
this.setState({ name: "testing state" });
- state should not be overly used for a better performance
Why setState()
Because it’s a method to inform the React VirtualDOM
that a part of the page has been changed. Rerender that part of the page at once. Without it, that part will never change.
React DOM compares the element and its children to the previous one, and only applies the DOM updates necessary to bring the DOM to the desired state.
Diffs between props and state
- props is passed from parent to child, state is private, meaning can not be accessed by anyone but the component in which it is defined
- props can not be changed, state is all for dynamic rendering
- props can not be changed, state can only be changed with
setState()
method - props is for passing data from parent to child, state is for managing data privately
a good blog to follow: codingdocs.com
Cem Eygi’s Youtube Channel: Cem Eygi Media to learn more about CSS, React JS for beginner
Lists and Keys
-
How to turn an array into a ‘list’
In JS it’s done through mapping:
const numbers = [1, 2, 3, 4, 5]; const listItems = numbers.map(number => <li>{number}</li>); // keys needed when mapping // then render it to the DOM ReactDOM.render(<ul>{listItems}</ul>, document.getElementById("root"));
-
Why keys are needed
To give the elements a stable identity, meaning that making sure that each element has its own identity so React can keep track which has been changed. In-depth explanation here.
-
Where to add keys
The keys are usually added when looping/mapping:
function ListItem(props) { return <li>{props.value}</li>; } function NumberItems(props) { const listItems = props.numbers.map(number => ( <ListItem key={number.toString()} value={number} /> )); return <ul>{listItem}</ul>; } const numbers = [1, 2, 3, 4, 5]; ReactDOM.render( <NumberItems numbers={numbers} />, document.getElementById("root") );
A good rule of thumb is that elements inside the
map()
call need keys. -
props.key
is NOT allowedAlthough
key={number.toString()}
is passed to the child component, however,key
is NOT accessable byprops.key
, you need to pass it in with another name, e.g.id={number.toString()}
, then you can access it byprops.id
Forms
In most cases, it’s convenient to have a JavaScript function that handles the submission of the form and has access to the data that the user entered into the form. The standard way to achieve this is with a technique called “controlled components”.
-
Controled Components
The purpose of ‘Controled Components’ is to make React state the Single Source of Truth. By attaching state values to displayed values, i.e. the displayed values are always depending on the state, therefore, by controling the value displayed, e.g. functions
onChange
to control keyboard strocks, functionsonClick
to control mouse clicks and functionsonSubmit
to control form submissions, any changes made by user will always triggersetState()
, hence, the state values reflect the latest state ALL THE TIME - SINGLE SOURCE OF TRUTH. -
Uncontrolled Components
-
Fully-Fledged Solution
check out formik for validation, keeping track of the visited fields, and handling form submission…
Listing State Up
React.Component API ref
🏄♂️ LIFECYCLE!
React lifecycle methods diagram cheatsheet
Function KEYWORDS
- ‘mount’: the action which brings the component to life, only after this action you can see the component on the page, before this action, the component is non-existent
- ‘unmount’: the action which takes the component/element out of the DOM
- ‘update’: the action which updates the state of this component
Actual FUNCTIONS
-
static getDerivedStateFromProps(props, state) { }
copy props into state -
componentWillMount = () => { }
do something before the render function, API transaction might not complete before rendering the page so not recommended to use AJAX calls here -
componentWillReceiveProps = () => { }
do something when the props passing in this component change -
componentWillUpdate = () => {}
-
shouldComponentUpdate = (nextProps, nextState) => { return a boolean to decide whether the component should update or not }
you can compare current state with nextState to decide whether to update the component -
getSnapshotBeforeUpdate(prevProps, prevState) {}
whatever returned here will be passed intocomponentDidUpdate
method as the 3rd argumentsnapshot
-
render() { return ... }
RENDER FUNCTION -
componentDidMount = () => { }
do something after the render function, API calls happening here -
componentDidUpdate = (prevProps, prevState, snapshot) => {}
do something when this component’s state is updated -
componentWillUnmount = () => {}
-
componentDidCatch(error, info) {}
catches errors without everything else crashing