Intro To React
Intro
React is a declarative frontend UI library created and maintained by Facebook. React is the most popular tool for creating beautiful responsive frontends. It was released to the public in 2013 to make code sharing easier by introducing the concept of a component to frontend development.
A component is a single UI element. This element can be as significant as a whole page or as simple as a small button. Components are the main building blocks of a react application and make it easy to share code in a single app or across multiple projects. The introduction of Components has made React into the most popular Frontend for the web and has made the component the default building block for all popular frontend frameworks Including Angular and Vue.
React and JSX
React uses a special subset of HTML called JSX. JSX stands for Javascript XML. Although it is possible to use React without JSX, we strongly advise against it. JSX is what made React the number one frontend tool on the web and allows for the combination of HTML, Javascript, and CSS in a single file. JSX is the same as HTML except for a few small differences.
Changes To HTML Attributes
One of the biggest changes from HTML to JSX is some attribute names have changed. Attribute name changes are because some attributes for HTML elements are javascript reserved keywords like for
and class
.
<div class="value"></div>
becomes<div className="container"></div>
<label for="email"/>
becomes<label htmlFor="email"/>
Inline Styling
The style attribute has also changed with JSX. The style attribute no longer takes a string of styles to be applied to an element. Styles that are to be applied now must be in a key-value paired object with the keys being camel-cased. Inline styling is an accepted practice in react, but just like in flat HTML. A better practice to use a global style sheet for the whole application or an individual style sheet for each component.
<div style={{backGroundColor: "rgb(255, 237, 43)", color:"green"}}></div>
Evaluating Expressions in JSX
import React from "react";
function App() {
const welcomeMessage = "JSX is Aswesome";
let mappedContent = ["one", "two", "three", "four", "five", "six"];
return (
<div className="App">
<h1>{welcomeMessage}</h1>
<ul>
{
mappedContent && mappedContent.map(index => <li> {index}</li>)
}
</ul>
<button onClick={() => {alert("Yay you clicked me")}}>Click Me</button>
</div>
);
}
JSX's first Letter is J for a reason. JSX makes writing javascript inside of markup extremely easy. No longer is it necessary to use querySelectors or getElementById to change the DOM. Javascript expressions can be written in directly in the markup using {}
. These expressions can be variables, function calls or dynamic attributes.
Props
import React from "react"
function Parent() {
return(
<h1>props example</h1>
<Child title="props are meh" />
)
}
function child(props) {
<h2>props are {props.title}</h2>
}
Props are a way of passing parameters or arguments into Components. Props allow for data and behavior to be passed from a parent component to a child component. Parent components control props by the parent component, and child components use them. As a general rule, props should only be passed down to three generations. Props are not a way of code sharing across highly coupled components; doing so is called prop drilling and is an anti-pattern.
Functional Programming
Functional Programming is an approach to writing software based on functions instead of objects or classes. Functional Programming emphasizes the immutability of data, the use of pure functions, and avoidance of side effects.
- Immutable data is data that, once declared, is not changed or mutated.
- Pure functions are functions that return the same output for the same input.
- A side effect is an operation that affects the outside environment where an operation takes place.
Using the functional paradigm in javascript makes applications easier to read and reason about, and helps avoid common pitfalls that occur while working in javascript.
React Provides Two Ways To Create Components
Class Based Components
import React from "react"
class App extends React.Component {
constructor(props){
super(props)
this.state={externalData:"bar"}
}
componentDidMount() {
this.setState({externalData:axios.get(`supercool.api/`)}:
}
componentDidUpdate() {
this.setState({externalData:axios.get(`supercool.api/`)}:
}
render(){
return(
<h1>{this.props.welcomeMessage}<h1>
{this.state.externalData.map({data}) => (<h2>data.title</h2>)}
)
}
}
Function Based Components
import React from "react"
function App(props) {
return(
<h1>{props.welcomeMessage}</h1>
)
}
Class based components have been the standard approach for creating React components. Unfortunately, class based components use state in a non standard way and use confusing lifecycle methods
Class-based components use a nonstandard syntax for handling state. Instead of having state variables accessible using the this
keyword, the standard for most OOP paradigms, state variables are only reachable by calling this.state
. The syntax of this.state
is confusing and makes it easy to mix up the difference between props, values passed into a component, and state variables, variables in memory controlled by the component.
Class-based components have confusing lifecycle methods that handle when a component mounts (when all the elements on a page have loaded) updates (when an internal change in a component occurs) and unmounts (the component is garbage collected). Logic becomes duplicated in the lifecycle methods since logic for mounting a component is almost Identical to updating a component. By having repeated logic in multiple methods, it becomes harder to reason and understand what a component is trying to accomplish and makes refactoring difficult.
Functional Components are cleaner and easier to understand. Unfortunately, Functional Components lacked persistent data and control of component rerenders. Functional Components were called dumb components or presentational components, while class-based components were considered smart components.
With the release of React 16.8 React Hooks were introduced. React Hooks allow for functional components to achieve all the same functionality of class-based components while maintaining an easier to read straight forward syntax. In Fullstack Web, we use Functional based components unless there is an extreme edge case that dictates the use of class-based components.
React Hooks
React introduced ten hooks with the release of React version 16.8, the two most important hooks being useState and useEffect. With the introduction of useState and useEffect functional components could now achieve the same behavior of class-based components while maintaining a simple, easy to read syntax.
import React, {useState, useEffect} from "react"
``
function App(props) {
const [foo, setFoo] = useState("bar")
useEffect(() => {
//preform actions related to when the component would have to rerender
setExternalData(axios.get("supercool.api"))
},
//watch for changes to values used by useEffect]
[externalData]);
return(
<h1>{props.welcomeMessage}</h1>
{externalData.map({data}) => (<h2>data.title</h2>)}
)
}
useState
The useState hook enables functional components to have state variables. A state variable in react is any variable whose value will persist after a component has rerendered.
const [foo, setFoo] = useState("bar");
foo
is the accessor for the variable it returns a readonly value.setFoo
is the mutator for the variable and allows for new values to be set for a state variable .useState()
makes react aware of the specfied state variable and returns the accessor and mutator for ituseState("bar")
in order to set an initial value for a state variable pass it as the arguement to the useState function call .
useEffect
The useEffect hook enables functional components to rerender when an internal change happens in a component. useEffect handles side effects that occur outside the component function, hence the name and dictates how the component should respond.
useEffect(() => {setExternalData(axios.get("supercool.api"))}, [watchedVariable]);
- useEffects syntax can be confusing and is unique to react
- the best way to think about useEffect is
useEffect(effects, inputs)
effect
is an anonymous function that contains function calls that have side effects.- Side-effects include API calls, accessing local storage or interacting with the dom
- failure to call functions with side-effects outside of useEffect causes a component to render continuously breaking the application.
inputs
is an array of values used by the functions called in the effects argument.- React watches the values inside of inputs and if they change rerenders the component.
React cheat sheet
https://dev.to/reedbarger/the-react-cheatsheet-for-2021-real-world-examples-5h28