SlideShare a Scribd company logo
Sergio Nakamura | nakamurasei.com hi@nakamurasei.com
An Introduction
To React For
Frontend Developers
An Introduction To React For Frontend Developers hi@nakamurasei.com
Disclaimer
Many of the techniques displayed aren’t exclusive to React. In fact, React is
built in JavaScript and as such all React features can be implemented in
JavaScript (and have existed for years, albeit with less flashy names).
However React offers a “framework”, a structure you can use to build your
applications. While not many people will implement a pub-sub method or a
helper method to simplify element creation, many people will use a
framework. You can use its features without knowing its inner workings,
without reinventing the wheel, and using the same conventions.
An Introduction To React For Frontend Developers hi@nakamurasei.com
Why React?
JavaScript has been used for over two decades to add interactivity to
webpages: adding, removing or modifying elements, responding to user
input and sending and receiving data from external sources.
React (just like Angular, Vue and many more) are frameworks built on
JavaScript that allow easier development of user interfaces.
1.
Declarative
Style
2.
Automatic
Updates
3.
Virtual
DOM
4.
Modular
Structure
An Introduction To React For Frontend Developers hi@nakamurasei.com
Why React?
Declarative Style
If you’ve previously used JavaScript you may have found yourself telling the
browser each step to make: select X element, set the content to Y, do Z
when clicked... Having to tell each step can be classified as an
“Imperative” style: forgetting a step may lead to errors, because the browser
just follows instructions, it doesn’t know what you’re actually looking for.
In React, you are following most of the time a “Declarative” style, you tell
what you want and provide the data. React does the work behind the
scenes to translate that information to the instructions your browser
understands.
1
An Introduction To React For Frontend Developers hi@nakamurasei.com
Why React?
Declarative Style
Let’s render a <button> and console.log when clicked, in Vanilla JS and React.
Vanilla JS React JS
1
const btn =
document.createElement(“button”);
//Create <button>
body.appendChild(btn); //Append to body
btn.innerText = “Click me”; //Change text
btn.addEventListener(“click”, () => {
console.log(“Clicked”);
}); //Log “Clicked” when clicked
import React from “react”;
export default function App() {
return (
<button onClick={() =>
console.log(“Clicked”)}>
Click me
</button>
);
} //I want a <button> with “Click me” as
text that logs “Clicked” when clicked
An Introduction To React For Frontend Developers hi@nakamurasei.com
Why React?
Automatic Updates
As your application grows adding an element and setting a value isn’t
enough: you may need to update its content as you receive new
information.
Without a framework as React, you may have to tell the browser to update the
elements every time we receive new information. While this doesn’t seem a
big deal at first it can get ugly fast.
Using React, all the elements depending on a piece of data get updated
automatically when the data changes.
2
An Introduction To React For Frontend Developers hi@nakamurasei.com
Why React?
Automatic Updates
Let’s see a simple button that +1 to a counter. The counter variable is seen in
two places at the time.
2
Vanilla JS React JS
let counter = 0; //Counter
const p = document.createElement(“p”); //Create a <p>
p.innerText = counter; //Set <p>’s text
body.appendChild(p); //Append <p> to the body
const btn = document.createElement(“button”);
//Create a <button>
btn.innerText = `+1 and make it ${counter + 1}`;
//Set <button>’s text
body.appendChild(btn);
//Append <button> to the body
btn.addEventListener(“click”, () => {
counter = counter ++; //Update the counter
p.innerText = counter; //Update <p>
btn.innerText = `+1 and make it ${counter + 1}`;
// Update <btn>
})
import React, {useState} from “react”;
export default function App() {
const [counter, setCounter] = useState(0);
return (<div>
<p>{counter}</p>
<button onClick={() =>
setCounter(counter++)}>
`+1 and make it ${counter + 1}`
</button>
</div>)
}
//All elements depending on counter will update when
counter changes value
An Introduction To React For Frontend Developers hi@nakamurasei.com
Why React?
Virtual DOM
In JavaScript one of the most performance degrading actions is updating
the DOM, that is the elements that compose your webpage. As such, wouldn’t
be great if we updated the DOM as less as possible? Enter the Virtual DOM.
With React we have two versions of the DOM: the one that’s being displayed
in the browser and an internal DOM that reflects the processed output by
React. By comparing both DOMs we can update only the elements that we
need. Without some technique like Virtual DOM we may need to update all
the elements even if we modified only one, incurring a performance hit.
3
An Introduction To React For Frontend Developers hi@nakamurasei.com
Why React?
Modular Structure
In React, each part of the UI can be divided in smaller components. This
makes coding more manageable and easier to work in a team, it allows the
production of self-contained components that can be reused easily and since
it’s JavaScript it allows data passing between components: no more storing
data in the DOM and in humongous global states.
4
An Introduction To React For Frontend Developers hi@nakamurasei.com
Why React?
Modular Structure
Let’s see how components can make our code more manageable.
4
Vanilla JS React JS
let fruits = [“mango”, “apple”, “banana”, “orange”];
const div = document.createElement(“div”);
//Create <div>
body.appendChild(div); //Append to body
function addFruits() {
fruits.forEach(fruit => {
const p = document.createElement(“p”);
p.innerText = fruit;
div.appendChild(p);})
}
addFruits();
import React, {useState, useEffect} from “react”;
import Fruits from “./Fruits.js”;
export default function App() {
const [fruits, setFruits] = useState([“mango”,
“apple”, “banana”, “orange”]);
return (<Fruits fruits={fruits}/>);
}
import React, {useState, useEffect} from “react”;
export default function Fruits(props) {
return (<div>{props.fruits.map(fruit=><p
key={fruit}>{fruit}</p>)}</div>);
}
//”fruits” was received from App() via props
App.js
Fruits.js
An Introduction To React For Frontend Developers hi@nakamurasei.com
React Basics
You can build a React application with either classes or functions. While
classes are useful when building complex components, in most cases using
functions will be more readable and concise.
You can build functional components in these ways. Note that we are
exporting the function, so we can use it in another place.
import React from “react”;
export default function App() {
return(<p>Hello World</p>);
}
import React from “react”;
const App = () => {
return(<p>Hello World</p>);
}
export default App;
An Introduction To React For Frontend Developers hi@nakamurasei.com
What you are seeing in orange isn’t HTML, is something called JSX, an
extension of JavaScript used in React. When you are using JSX you are
actually calling a function named “createElement” which outputs the HTML
you are expecting.
React Basics
JSX
import React from “react”;
export default function App() {
return(<p>Hello World</p>);
}
An Introduction To React For Frontend Developers hi@nakamurasei.com
React Basics
JSX
JSX elements must be closed at all times. While most HTML elements follow
the <></> structure, some elements don’t have an end tag (like <input> or
<img>). In those cases you must add a / right before >, effectively closing it.
<input type=”submit”> <input type=”submit”/>
HTML React’s JSX
An Introduction To React For Frontend Developers hi@nakamurasei.com
React Basics
JSX
As we are seeing, JSX isn’t an exact copy of HTML. If you want to style your
components using CSS, the “class” property isn’t allowed. Instead, use
“className”.
<p class=”hello”>Hello</p> <p className=”hello”>Hello</p>
HTML React’s JSX
An Introduction To React For Frontend Developers hi@nakamurasei.com
React Basics
JSX
One of the advantages of JSX is that we can use JavaScript code instead of
strings. To do so we wrap our code in {}. This allows us to use variables,
render CSS class names conditionally, call functions and more.
<p className=”hello”>{message}</p>
//<p>’s content is the variable “message”.
React’s JSX
An Introduction To React For Frontend Developers hi@nakamurasei.com
React Basics
JSX - Using JS Code inside {}
The code inside {} must always return something (even null).
We can’t add more than one line (as in separate instructions divided by ;),
however functions can have multiples lines inside it.
<p className=”hello”>{
function renderStuff () {
return “Hello”
};
renderStuff()}
</p>
<p className=”hello”>{
“Hello”
}</p>
Invalid: Separate instructions OK
An Introduction To React For Frontend Developers hi@nakamurasei.com
React Basics
JSX - Using JS Code inside {}
We can’t use if as it doesn’t always return something. We can use a ternary
expression instead, where the else clause returns null.
<p className=”hello”>{
if(name === “Kentaro”){
return “You are
Kentaro”}
}</p>
<p className=”hello”>{
name === “Kentaro” ? “You are
Kentaro” : null
}</p>
Invalid: if OK
An Introduction To React For Frontend Developers hi@nakamurasei.com
React Basics
JSX - Using JS Code inside {}
To replace an if else clause use the ternary expression in the same way.
<p className=”hello”>{
if(name === “Kentaro”){
return “You are
Kentaro”} else {
return “You are not Kentaro”
}
}</p>
<p className=”hello”>{
name === “Kentaro” ? “You are
Kentaro” : “You are not Kentaro”
}</p>
Invalid: if OK
An Introduction To React For Frontend Developers hi@nakamurasei.com
React Basics
JSX - Using JS Code inside {}
We can’t add loops (such as for or forEach). However we can use array’s map,
since it will always return an array.
<div>{
names.forEach(name => <p
key={name}>{name}</p>)}
</div>
<div>{
names.map(name => <p
key={name}>{name}</p>)
}</div>
Invalid: forEach
<div>{
for(i = 0, n=names.length; i<n; i++){
return <p key={names[i]}>names[i]</p>}
}</div>
Invalid: for
OK
An Introduction To React For Frontend Developers hi@nakamurasei.com
import React from “react”;
import MyFunction from “./MyFunction.js”;
const App = () => {
return <MyFunction name=”Kentaro”/>;
}
export default App;
App.js
import React from “react”;
const MyFunction = (props) => {
return <p>{props.name}</p>;
}
export default MyFunction;
MyFunction.js
React Basics
Modularity
By splitting your application in several files code reuse and teamwork become
easier. To import a component use “import” at the top of your file.
An Introduction To React For Frontend Developers hi@nakamurasei.com
React Basics
Using state inside components
To store information inside our components we can use “useState”, a React
Hook (function that enables access to the state and lifecycle features of
React.)
import React, {useState} from “react”; import React, {useState} from “react”;
export default function App() {
const [counter, setCounter] =
useState(0);
return <p>{counter}</p>;
}
1: Import useState at the top 2. Call useState inside the function
An Introduction To React For Frontend Developers hi@nakamurasei.com
React Basics
Anatomy of useState
const [counter, setCounter] = useState(0);
1: Pick a name for the
variable that will hold the
state’s value.
2: This is the function that will
set the state’s value.
By convention name it “set” +
the name picked in 1
(camelCase).
3: This is the initial value of
the state. Ideally set it to the
same type as the expected
value. For example, if you are
expecting a number you can
set it to 0.
Functions, variables, even null
and undefined is OK.
An Introduction To React For Frontend Developers hi@nakamurasei.com
React Basics
useState example
import React, {useState} from “react”;
export default function App() {
const [counter, setCounter] =
useState(0);
return (<div>
<p>{counter}</p>
<button onClick={() =>
setCounter(counter + 1)}>+1</button>
</div>
)
}
1: <p/> will hold the counter value. At
initialization its value will be 0, as defined in
useState.
2: When <button/> is clicked, the counter’s
value will be incremented by 1. Automatically,
every place that holds “counter” will update its
value.
An Introduction To React For Frontend Developers hi@nakamurasei.com
React Basics
useEffect
Another React Hook is “useEffect”. Whatever instructions are inside of
useEffect will get executed whenever there’s an update to its dependences.
This lets us fetch data at component mount, execute functions when new
information is received and more.
import React, {useEffect} from “react”; import React, {useEffect} from “react”;
export default function App() {
useEffect(() => {
//Place code here
}, []);
return <p>Hello world</p>;
}
1: Import useEffect at the top 2. Call useEffect inside the function
An Introduction To React For Frontend Developers hi@nakamurasei.com
React Basics
useEffect’s Behaviour
The behaviour of useEffect changes depending on the dependencies defined
in the [] at the end.
useEffect(() => {
//Place code here
}, []);
Component mount
If nothing is defined inside [], the code inside
useEffect will execute only once at
component mount. This replaces React’s
lifecycle method componentDidMount.
useEffect(() => {
//Place code here
}, [varName]);
Update at dependency change
The code will execute once at component
mount and everytime there’s a change of the
dependencies defined inside []. You can add as
many dependencies you wish.
An Introduction To React For Frontend Developers hi@nakamurasei.com
React Basics
useEffect example
import React, {useState, useEffect} from
“react”;
export default function App() {
const [counter, setCounter] =
useState(0);
useEffect(()=>{
console.log(`Counter value is
${counter}`);
}, [counter]);
return (<div>
<p>{counter}</p>
<button onClick={() =>
setCounter(counter + 1)}>+1</button>
</div>
)
}
Because “counter” is defined as a dependency
of useEffect, it will console.log every time
“counter” is incremented.
Sergio Nakamura | nakamurasei.com hi@nakamurasei.com
Thank you!
Ad

More Related Content

What's hot (20)

Angular 8
Angular 8 Angular 8
Angular 8
Sunil OS
 
Vaadin & Web Components
Vaadin & Web ComponentsVaadin & Web Components
Vaadin & Web Components
Joonas Lehtinen
 
Vaadin Introduction, 7.3 edition
Vaadin Introduction, 7.3 editionVaadin Introduction, 7.3 edition
Vaadin Introduction, 7.3 edition
Joonas Lehtinen
 
Beginning AngularJS
Beginning AngularJSBeginning AngularJS
Beginning AngularJS
Troy Miles
 
Intoduction to Angularjs
Intoduction to AngularjsIntoduction to Angularjs
Intoduction to Angularjs
Gaurav Agrawal
 
Adding User Management to Node.js
Adding User Management to Node.jsAdding User Management to Node.js
Adding User Management to Node.js
Dev_Events
 
Part 1 implementing a simple_web_service
Part 1 implementing a simple_web_servicePart 1 implementing a simple_web_service
Part 1 implementing a simple_web_service
krishmdkk
 
Web Components for Java Developers
Web Components for Java DevelopersWeb Components for Java Developers
Web Components for Java Developers
Joonas Lehtinen
 
Flutter State Management Using GetX.pdf
Flutter State Management Using GetX.pdfFlutter State Management Using GetX.pdf
Flutter State Management Using GetX.pdf
Katy Slemon
 
Introduction to Vaadin
Introduction to VaadinIntroduction to Vaadin
Introduction to Vaadin
netomi
 
GWT Training - Session 1/3
GWT Training - Session 1/3GWT Training - Session 1/3
GWT Training - Session 1/3
Faiz Bashir
 
Workshop: Building Vaadin add-ons
Workshop: Building Vaadin add-onsWorkshop: Building Vaadin add-ons
Workshop: Building Vaadin add-ons
Sami Ekblad
 
JOSA TechTalks - Better Web Apps with React and Redux
JOSA TechTalks - Better Web Apps with React and ReduxJOSA TechTalks - Better Web Apps with React and Redux
JOSA TechTalks - Better Web Apps with React and Redux
Jordan Open Source Association
 
React Js Simplified
React Js SimplifiedReact Js Simplified
React Js Simplified
Sunil Yadav
 
Angular 7 Firebase5 CRUD Operations with Reactive Forms
Angular 7 Firebase5 CRUD Operations with Reactive FormsAngular 7 Firebase5 CRUD Operations with Reactive Forms
Angular 7 Firebase5 CRUD Operations with Reactive Forms
Digamber Singh
 
JSLab. Алексей Волков. "React на практике"
JSLab. Алексей Волков. "React на практике"JSLab. Алексей Волков. "React на практике"
JSLab. Алексей Волков. "React на практике"
GeeksLab Odessa
 
Angular JS2 Training Session #2
Angular JS2 Training Session #2Angular JS2 Training Session #2
Angular JS2 Training Session #2
Paras Mendiratta
 
Hackathon - Building vaadin add on components
Hackathon - Building vaadin add on componentsHackathon - Building vaadin add on components
Hackathon - Building vaadin add on components
Joonas Lehtinen
 
An introduction to AngularJS
An introduction to AngularJSAn introduction to AngularJS
An introduction to AngularJS
Yogesh singh
 
Universal JS Web Applications with React - Luciano Mammino - Codemotion Rome ...
Universal JS Web Applications with React - Luciano Mammino - Codemotion Rome ...Universal JS Web Applications with React - Luciano Mammino - Codemotion Rome ...
Universal JS Web Applications with React - Luciano Mammino - Codemotion Rome ...
Luciano Mammino
 
Angular 8
Angular 8 Angular 8
Angular 8
Sunil OS
 
Vaadin Introduction, 7.3 edition
Vaadin Introduction, 7.3 editionVaadin Introduction, 7.3 edition
Vaadin Introduction, 7.3 edition
Joonas Lehtinen
 
Beginning AngularJS
Beginning AngularJSBeginning AngularJS
Beginning AngularJS
Troy Miles
 
Intoduction to Angularjs
Intoduction to AngularjsIntoduction to Angularjs
Intoduction to Angularjs
Gaurav Agrawal
 
Adding User Management to Node.js
Adding User Management to Node.jsAdding User Management to Node.js
Adding User Management to Node.js
Dev_Events
 
Part 1 implementing a simple_web_service
Part 1 implementing a simple_web_servicePart 1 implementing a simple_web_service
Part 1 implementing a simple_web_service
krishmdkk
 
Web Components for Java Developers
Web Components for Java DevelopersWeb Components for Java Developers
Web Components for Java Developers
Joonas Lehtinen
 
Flutter State Management Using GetX.pdf
Flutter State Management Using GetX.pdfFlutter State Management Using GetX.pdf
Flutter State Management Using GetX.pdf
Katy Slemon
 
Introduction to Vaadin
Introduction to VaadinIntroduction to Vaadin
Introduction to Vaadin
netomi
 
GWT Training - Session 1/3
GWT Training - Session 1/3GWT Training - Session 1/3
GWT Training - Session 1/3
Faiz Bashir
 
Workshop: Building Vaadin add-ons
Workshop: Building Vaadin add-onsWorkshop: Building Vaadin add-ons
Workshop: Building Vaadin add-ons
Sami Ekblad
 
React Js Simplified
React Js SimplifiedReact Js Simplified
React Js Simplified
Sunil Yadav
 
Angular 7 Firebase5 CRUD Operations with Reactive Forms
Angular 7 Firebase5 CRUD Operations with Reactive FormsAngular 7 Firebase5 CRUD Operations with Reactive Forms
Angular 7 Firebase5 CRUD Operations with Reactive Forms
Digamber Singh
 
JSLab. Алексей Волков. "React на практике"
JSLab. Алексей Волков. "React на практике"JSLab. Алексей Волков. "React на практике"
JSLab. Алексей Волков. "React на практике"
GeeksLab Odessa
 
Angular JS2 Training Session #2
Angular JS2 Training Session #2Angular JS2 Training Session #2
Angular JS2 Training Session #2
Paras Mendiratta
 
Hackathon - Building vaadin add on components
Hackathon - Building vaadin add on componentsHackathon - Building vaadin add on components
Hackathon - Building vaadin add on components
Joonas Lehtinen
 
An introduction to AngularJS
An introduction to AngularJSAn introduction to AngularJS
An introduction to AngularJS
Yogesh singh
 
Universal JS Web Applications with React - Luciano Mammino - Codemotion Rome ...
Universal JS Web Applications with React - Luciano Mammino - Codemotion Rome ...Universal JS Web Applications with React - Luciano Mammino - Codemotion Rome ...
Universal JS Web Applications with React - Luciano Mammino - Codemotion Rome ...
Luciano Mammino
 

Similar to Introduction to React for Frontend Developers (20)

React: JSX and Top Level API
React: JSX and Top Level APIReact: JSX and Top Level API
React: JSX and Top Level API
Fabio Biondi
 
Server side rendering with React and Symfony
Server side rendering with React and SymfonyServer side rendering with React and Symfony
Server side rendering with React and Symfony
Ignacio Martín
 
React & Redux for noobs
React & Redux for noobsReact & Redux for noobs
React & Redux for noobs
[T]echdencias
 
REACT pdf.docx
REACT pdf.docxREACT pdf.docx
REACT pdf.docx
PSK Technolgies Pvt. Ltd. IT Company Nagpur
 
React JS: A Secret Preview
React JS: A Secret PreviewReact JS: A Secret Preview
React JS: A Secret Preview
valuebound
 
Fundamental concepts of react js
Fundamental concepts of react jsFundamental concepts of react js
Fundamental concepts of react js
StephieJohn
 
Ways to Set Focus on an Input Field After Rendering in React.pptx
Ways to Set Focus on an Input Field After Rendering in React.pptxWays to Set Focus on an Input Field After Rendering in React.pptx
Ways to Set Focus on an Input Field After Rendering in React.pptx
BOSC Tech Labs
 
ReactJS.pptx
ReactJS.pptxReactJS.pptx
ReactJS.pptx
SamyakShetty2
 
Tech Talk on ReactJS
Tech Talk on ReactJSTech Talk on ReactJS
Tech Talk on ReactJS
Atlogys Technical Consulting
 
React outbox
React outboxReact outbox
React outbox
Angela Lehru
 
Build web apps with react js
Build web apps with react jsBuild web apps with react js
Build web apps with react js
dhanushkacnd
 
Lessons from a year of building apps with React Native
Lessons from a year of building apps with React NativeLessons from a year of building apps with React Native
Lessons from a year of building apps with React Native
Ryan Boland
 
Full Stack React Workshop [CSSC x GDSC]
Full Stack React Workshop [CSSC x GDSC]Full Stack React Workshop [CSSC x GDSC]
Full Stack React Workshop [CSSC x GDSC]
GDSC UofT Mississauga
 
How to create components in react js
How to create components in react jsHow to create components in react js
How to create components in react js
BOSC Tech Labs
 
React Basic and Advance || React Basic
React Basic and Advance   || React BasicReact Basic and Advance   || React Basic
React Basic and Advance || React Basic
rafaqathussainc077
 
A full introductory guide to React
A full introductory guide to ReactA full introductory guide to React
A full introductory guide to React
Jean Carlo Emer
 
Паразитируем на React-экосистеме (Angular 4+) / Алексей Охрименко (IPONWEB)
Паразитируем на React-экосистеме (Angular 4+) / Алексей Охрименко (IPONWEB)Паразитируем на React-экосистеме (Angular 4+) / Алексей Охрименко (IPONWEB)
Паразитируем на React-экосистеме (Angular 4+) / Алексей Охрименко (IPONWEB)
Ontico
 
React JS Interview Questions PDF By ScholarHat
React JS Interview Questions PDF By ScholarHatReact JS Interview Questions PDF By ScholarHat
React JS Interview Questions PDF By ScholarHat
Scholarhat
 
Building user interface with react
Building user interface with reactBuilding user interface with react
Building user interface with react
Amit Thakkar
 
React Native +Redux + ES6 (Updated)
React Native +Redux + ES6 (Updated)React Native +Redux + ES6 (Updated)
React Native +Redux + ES6 (Updated)
Chiew Carol
 
React: JSX and Top Level API
React: JSX and Top Level APIReact: JSX and Top Level API
React: JSX and Top Level API
Fabio Biondi
 
Server side rendering with React and Symfony
Server side rendering with React and SymfonyServer side rendering with React and Symfony
Server side rendering with React and Symfony
Ignacio Martín
 
React & Redux for noobs
React & Redux for noobsReact & Redux for noobs
React & Redux for noobs
[T]echdencias
 
React JS: A Secret Preview
React JS: A Secret PreviewReact JS: A Secret Preview
React JS: A Secret Preview
valuebound
 
Fundamental concepts of react js
Fundamental concepts of react jsFundamental concepts of react js
Fundamental concepts of react js
StephieJohn
 
Ways to Set Focus on an Input Field After Rendering in React.pptx
Ways to Set Focus on an Input Field After Rendering in React.pptxWays to Set Focus on an Input Field After Rendering in React.pptx
Ways to Set Focus on an Input Field After Rendering in React.pptx
BOSC Tech Labs
 
Build web apps with react js
Build web apps with react jsBuild web apps with react js
Build web apps with react js
dhanushkacnd
 
Lessons from a year of building apps with React Native
Lessons from a year of building apps with React NativeLessons from a year of building apps with React Native
Lessons from a year of building apps with React Native
Ryan Boland
 
Full Stack React Workshop [CSSC x GDSC]
Full Stack React Workshop [CSSC x GDSC]Full Stack React Workshop [CSSC x GDSC]
Full Stack React Workshop [CSSC x GDSC]
GDSC UofT Mississauga
 
How to create components in react js
How to create components in react jsHow to create components in react js
How to create components in react js
BOSC Tech Labs
 
React Basic and Advance || React Basic
React Basic and Advance   || React BasicReact Basic and Advance   || React Basic
React Basic and Advance || React Basic
rafaqathussainc077
 
A full introductory guide to React
A full introductory guide to ReactA full introductory guide to React
A full introductory guide to React
Jean Carlo Emer
 
Паразитируем на React-экосистеме (Angular 4+) / Алексей Охрименко (IPONWEB)
Паразитируем на React-экосистеме (Angular 4+) / Алексей Охрименко (IPONWEB)Паразитируем на React-экосистеме (Angular 4+) / Алексей Охрименко (IPONWEB)
Паразитируем на React-экосистеме (Angular 4+) / Алексей Охрименко (IPONWEB)
Ontico
 
React JS Interview Questions PDF By ScholarHat
React JS Interview Questions PDF By ScholarHatReact JS Interview Questions PDF By ScholarHat
React JS Interview Questions PDF By ScholarHat
Scholarhat
 
Building user interface with react
Building user interface with reactBuilding user interface with react
Building user interface with react
Amit Thakkar
 
React Native +Redux + ES6 (Updated)
React Native +Redux + ES6 (Updated)React Native +Redux + ES6 (Updated)
React Native +Redux + ES6 (Updated)
Chiew Carol
 
Ad

Recently uploaded (20)

APNIC Policy Update and Participation, presented at TWNIC 43rd IP Open Policy...
APNIC Policy Update and Participation, presented at TWNIC 43rd IP Open Policy...APNIC Policy Update and Participation, presented at TWNIC 43rd IP Open Policy...
APNIC Policy Update and Participation, presented at TWNIC 43rd IP Open Policy...
APNIC
 
Presentation Mehdi Monitorama 2022 Cancer and Monitoring
Presentation Mehdi Monitorama 2022 Cancer and MonitoringPresentation Mehdi Monitorama 2022 Cancer and Monitoring
Presentation Mehdi Monitorama 2022 Cancer and Monitoring
mdaoudi
 
Biochemistry and Biomolecules - Science - 9th Grade _ by Slidesgo.pptx
Biochemistry and Biomolecules - Science - 9th Grade _ by Slidesgo.pptxBiochemistry and Biomolecules - Science - 9th Grade _ by Slidesgo.pptx
Biochemistry and Biomolecules - Science - 9th Grade _ by Slidesgo.pptx
SergioBarreno2
 
Cloud-to-cloud Migration presentation.pptx
Cloud-to-cloud Migration presentation.pptxCloud-to-cloud Migration presentation.pptx
Cloud-to-cloud Migration presentation.pptx
marketing140789
 
ProjectArtificial Intelligence Good or Evil.pptx
ProjectArtificial Intelligence Good or Evil.pptxProjectArtificial Intelligence Good or Evil.pptx
ProjectArtificial Intelligence Good or Evil.pptx
OlenaKotovska
 
34 Turban Electronic Commerce 2018_ A Managerial and Social Networks Perspect...
34 Turban Electronic Commerce 2018_ A Managerial and Social Networks Perspect...34 Turban Electronic Commerce 2018_ A Managerial and Social Networks Perspect...
34 Turban Electronic Commerce 2018_ A Managerial and Social Networks Perspect...
Nguyễn Minh
 
AG-FIRMA Ai Agent for Agriculture | RAG ..
AG-FIRMA Ai Agent for Agriculture  | RAG ..AG-FIRMA Ai Agent for Agriculture  | RAG ..
AG-FIRMA Ai Agent for Agriculture | RAG ..
Anass Nabil
 
34 Advances in Mobile Commerce Technologies (2003).pdf
34 Advances in Mobile Commerce Technologies (2003).pdf34 Advances in Mobile Commerce Technologies (2003).pdf
34 Advances in Mobile Commerce Technologies (2003).pdf
Nguyễn Minh
 
Global Networking Trends, presented at TWNIC 43rd IP Open Policy Meeting
Global Networking Trends, presented at TWNIC 43rd IP Open Policy MeetingGlobal Networking Trends, presented at TWNIC 43rd IP Open Policy Meeting
Global Networking Trends, presented at TWNIC 43rd IP Open Policy Meeting
APNIC
 
美国文凭明尼苏达大学莫里斯分校毕业证范本UMM学位证书
美国文凭明尼苏达大学莫里斯分校毕业证范本UMM学位证书美国文凭明尼苏达大学莫里斯分校毕业证范本UMM学位证书
美国文凭明尼苏达大学莫里斯分校毕业证范本UMM学位证书
Taqyea
 
34 Global Mobile Commerce_ Strategies, Implementation and Case Studies (Premi...
34 Global Mobile Commerce_ Strategies, Implementation and Case Studies (Premi...34 Global Mobile Commerce_ Strategies, Implementation and Case Studies (Premi...
34 Global Mobile Commerce_ Strategies, Implementation and Case Studies (Premi...
Nguyễn Minh
 
34 E-commerce - business, technology and society (2022).pdf
34 E-commerce - business, technology and society (2022).pdf34 E-commerce - business, technology and society (2022).pdf
34 E-commerce - business, technology and society (2022).pdf
Nguyễn Minh
 
23 Introduction to E-Commerce ( PDFDrive ) (1).pdf
23 Introduction to E-Commerce ( PDFDrive ) (1).pdf23 Introduction to E-Commerce ( PDFDrive ) (1).pdf
23 Introduction to E-Commerce ( PDFDrive ) (1).pdf
Nguyễn Minh
 
学生卡英国RCA毕业证皇家艺术学院电子毕业证学历证书
学生卡英国RCA毕业证皇家艺术学院电子毕业证学历证书学生卡英国RCA毕业证皇家艺术学院电子毕业证学历证书
学生卡英国RCA毕业证皇家艺术学院电子毕业证学历证书
Taqyea
 
34 E-commerce and M-commerce technologies (P. Candace Deans 2006).pdf
34 E-commerce and M-commerce technologies (P. Candace Deans 2006).pdf34 E-commerce and M-commerce technologies (P. Candace Deans 2006).pdf
34 E-commerce and M-commerce technologies (P. Candace Deans 2006).pdf
Nguyễn Minh
 
水印成绩单加拿大Mohawk文凭莫霍克学院在读证明毕业证
水印成绩单加拿大Mohawk文凭莫霍克学院在读证明毕业证水印成绩单加拿大Mohawk文凭莫霍克学院在读证明毕业证
水印成绩单加拿大Mohawk文凭莫霍克学院在读证明毕业证
Taqyea
 
34 Mobile Electronic Commerce_ Foundations, Development, and Applications (20...
34 Mobile Electronic Commerce_ Foundations, Development, and Applications (20...34 Mobile Electronic Commerce_ Foundations, Development, and Applications (20...
34 Mobile Electronic Commerce_ Foundations, Development, and Applications (20...
Nguyễn Minh
 
Fractures In Chronic Kidney Disease Patients - Copy (3).pptx
Fractures In Chronic Kidney Disease Patients - Copy (3).pptxFractures In Chronic Kidney Disease Patients - Copy (3).pptx
Fractures In Chronic Kidney Disease Patients - Copy (3).pptx
ChaitanJaunky1
 
34 Mobile Payment (Thomas Lerner (auth.).pdf
34 Mobile Payment (Thomas Lerner (auth.).pdf34 Mobile Payment (Thomas Lerner (auth.).pdf
34 Mobile Payment (Thomas Lerner (auth.).pdf
Nguyễn Minh
 
GiacomoVacca - WebRTC - troubleshooting media negotiation.pdf
GiacomoVacca - WebRTC - troubleshooting media negotiation.pdfGiacomoVacca - WebRTC - troubleshooting media negotiation.pdf
GiacomoVacca - WebRTC - troubleshooting media negotiation.pdf
Giacomo Vacca
 
APNIC Policy Update and Participation, presented at TWNIC 43rd IP Open Policy...
APNIC Policy Update and Participation, presented at TWNIC 43rd IP Open Policy...APNIC Policy Update and Participation, presented at TWNIC 43rd IP Open Policy...
APNIC Policy Update and Participation, presented at TWNIC 43rd IP Open Policy...
APNIC
 
Presentation Mehdi Monitorama 2022 Cancer and Monitoring
Presentation Mehdi Monitorama 2022 Cancer and MonitoringPresentation Mehdi Monitorama 2022 Cancer and Monitoring
Presentation Mehdi Monitorama 2022 Cancer and Monitoring
mdaoudi
 
Biochemistry and Biomolecules - Science - 9th Grade _ by Slidesgo.pptx
Biochemistry and Biomolecules - Science - 9th Grade _ by Slidesgo.pptxBiochemistry and Biomolecules - Science - 9th Grade _ by Slidesgo.pptx
Biochemistry and Biomolecules - Science - 9th Grade _ by Slidesgo.pptx
SergioBarreno2
 
Cloud-to-cloud Migration presentation.pptx
Cloud-to-cloud Migration presentation.pptxCloud-to-cloud Migration presentation.pptx
Cloud-to-cloud Migration presentation.pptx
marketing140789
 
ProjectArtificial Intelligence Good or Evil.pptx
ProjectArtificial Intelligence Good or Evil.pptxProjectArtificial Intelligence Good or Evil.pptx
ProjectArtificial Intelligence Good or Evil.pptx
OlenaKotovska
 
34 Turban Electronic Commerce 2018_ A Managerial and Social Networks Perspect...
34 Turban Electronic Commerce 2018_ A Managerial and Social Networks Perspect...34 Turban Electronic Commerce 2018_ A Managerial and Social Networks Perspect...
34 Turban Electronic Commerce 2018_ A Managerial and Social Networks Perspect...
Nguyễn Minh
 
AG-FIRMA Ai Agent for Agriculture | RAG ..
AG-FIRMA Ai Agent for Agriculture  | RAG ..AG-FIRMA Ai Agent for Agriculture  | RAG ..
AG-FIRMA Ai Agent for Agriculture | RAG ..
Anass Nabil
 
34 Advances in Mobile Commerce Technologies (2003).pdf
34 Advances in Mobile Commerce Technologies (2003).pdf34 Advances in Mobile Commerce Technologies (2003).pdf
34 Advances in Mobile Commerce Technologies (2003).pdf
Nguyễn Minh
 
Global Networking Trends, presented at TWNIC 43rd IP Open Policy Meeting
Global Networking Trends, presented at TWNIC 43rd IP Open Policy MeetingGlobal Networking Trends, presented at TWNIC 43rd IP Open Policy Meeting
Global Networking Trends, presented at TWNIC 43rd IP Open Policy Meeting
APNIC
 
美国文凭明尼苏达大学莫里斯分校毕业证范本UMM学位证书
美国文凭明尼苏达大学莫里斯分校毕业证范本UMM学位证书美国文凭明尼苏达大学莫里斯分校毕业证范本UMM学位证书
美国文凭明尼苏达大学莫里斯分校毕业证范本UMM学位证书
Taqyea
 
34 Global Mobile Commerce_ Strategies, Implementation and Case Studies (Premi...
34 Global Mobile Commerce_ Strategies, Implementation and Case Studies (Premi...34 Global Mobile Commerce_ Strategies, Implementation and Case Studies (Premi...
34 Global Mobile Commerce_ Strategies, Implementation and Case Studies (Premi...
Nguyễn Minh
 
34 E-commerce - business, technology and society (2022).pdf
34 E-commerce - business, technology and society (2022).pdf34 E-commerce - business, technology and society (2022).pdf
34 E-commerce - business, technology and society (2022).pdf
Nguyễn Minh
 
23 Introduction to E-Commerce ( PDFDrive ) (1).pdf
23 Introduction to E-Commerce ( PDFDrive ) (1).pdf23 Introduction to E-Commerce ( PDFDrive ) (1).pdf
23 Introduction to E-Commerce ( PDFDrive ) (1).pdf
Nguyễn Minh
 
学生卡英国RCA毕业证皇家艺术学院电子毕业证学历证书
学生卡英国RCA毕业证皇家艺术学院电子毕业证学历证书学生卡英国RCA毕业证皇家艺术学院电子毕业证学历证书
学生卡英国RCA毕业证皇家艺术学院电子毕业证学历证书
Taqyea
 
34 E-commerce and M-commerce technologies (P. Candace Deans 2006).pdf
34 E-commerce and M-commerce technologies (P. Candace Deans 2006).pdf34 E-commerce and M-commerce technologies (P. Candace Deans 2006).pdf
34 E-commerce and M-commerce technologies (P. Candace Deans 2006).pdf
Nguyễn Minh
 
水印成绩单加拿大Mohawk文凭莫霍克学院在读证明毕业证
水印成绩单加拿大Mohawk文凭莫霍克学院在读证明毕业证水印成绩单加拿大Mohawk文凭莫霍克学院在读证明毕业证
水印成绩单加拿大Mohawk文凭莫霍克学院在读证明毕业证
Taqyea
 
34 Mobile Electronic Commerce_ Foundations, Development, and Applications (20...
34 Mobile Electronic Commerce_ Foundations, Development, and Applications (20...34 Mobile Electronic Commerce_ Foundations, Development, and Applications (20...
34 Mobile Electronic Commerce_ Foundations, Development, and Applications (20...
Nguyễn Minh
 
Fractures In Chronic Kidney Disease Patients - Copy (3).pptx
Fractures In Chronic Kidney Disease Patients - Copy (3).pptxFractures In Chronic Kidney Disease Patients - Copy (3).pptx
Fractures In Chronic Kidney Disease Patients - Copy (3).pptx
ChaitanJaunky1
 
34 Mobile Payment (Thomas Lerner (auth.).pdf
34 Mobile Payment (Thomas Lerner (auth.).pdf34 Mobile Payment (Thomas Lerner (auth.).pdf
34 Mobile Payment (Thomas Lerner (auth.).pdf
Nguyễn Minh
 
GiacomoVacca - WebRTC - troubleshooting media negotiation.pdf
GiacomoVacca - WebRTC - troubleshooting media negotiation.pdfGiacomoVacca - WebRTC - troubleshooting media negotiation.pdf
GiacomoVacca - WebRTC - troubleshooting media negotiation.pdf
Giacomo Vacca
 
Ad

Introduction to React for Frontend Developers

  • 1. Sergio Nakamura | nakamurasei.com hi@nakamurasei.com An Introduction To React For Frontend Developers
  • 2. An Introduction To React For Frontend Developers hi@nakamurasei.com Disclaimer Many of the techniques displayed aren’t exclusive to React. In fact, React is built in JavaScript and as such all React features can be implemented in JavaScript (and have existed for years, albeit with less flashy names). However React offers a “framework”, a structure you can use to build your applications. While not many people will implement a pub-sub method or a helper method to simplify element creation, many people will use a framework. You can use its features without knowing its inner workings, without reinventing the wheel, and using the same conventions.
  • 3. An Introduction To React For Frontend Developers hi@nakamurasei.com Why React? JavaScript has been used for over two decades to add interactivity to webpages: adding, removing or modifying elements, responding to user input and sending and receiving data from external sources. React (just like Angular, Vue and many more) are frameworks built on JavaScript that allow easier development of user interfaces. 1. Declarative Style 2. Automatic Updates 3. Virtual DOM 4. Modular Structure
  • 4. An Introduction To React For Frontend Developers hi@nakamurasei.com Why React? Declarative Style If you’ve previously used JavaScript you may have found yourself telling the browser each step to make: select X element, set the content to Y, do Z when clicked... Having to tell each step can be classified as an “Imperative” style: forgetting a step may lead to errors, because the browser just follows instructions, it doesn’t know what you’re actually looking for. In React, you are following most of the time a “Declarative” style, you tell what you want and provide the data. React does the work behind the scenes to translate that information to the instructions your browser understands. 1
  • 5. An Introduction To React For Frontend Developers hi@nakamurasei.com Why React? Declarative Style Let’s render a <button> and console.log when clicked, in Vanilla JS and React. Vanilla JS React JS 1 const btn = document.createElement(“button”); //Create <button> body.appendChild(btn); //Append to body btn.innerText = “Click me”; //Change text btn.addEventListener(“click”, () => { console.log(“Clicked”); }); //Log “Clicked” when clicked import React from “react”; export default function App() { return ( <button onClick={() => console.log(“Clicked”)}> Click me </button> ); } //I want a <button> with “Click me” as text that logs “Clicked” when clicked
  • 6. An Introduction To React For Frontend Developers hi@nakamurasei.com Why React? Automatic Updates As your application grows adding an element and setting a value isn’t enough: you may need to update its content as you receive new information. Without a framework as React, you may have to tell the browser to update the elements every time we receive new information. While this doesn’t seem a big deal at first it can get ugly fast. Using React, all the elements depending on a piece of data get updated automatically when the data changes. 2
  • 7. An Introduction To React For Frontend Developers hi@nakamurasei.com Why React? Automatic Updates Let’s see a simple button that +1 to a counter. The counter variable is seen in two places at the time. 2 Vanilla JS React JS let counter = 0; //Counter const p = document.createElement(“p”); //Create a <p> p.innerText = counter; //Set <p>’s text body.appendChild(p); //Append <p> to the body const btn = document.createElement(“button”); //Create a <button> btn.innerText = `+1 and make it ${counter + 1}`; //Set <button>’s text body.appendChild(btn); //Append <button> to the body btn.addEventListener(“click”, () => { counter = counter ++; //Update the counter p.innerText = counter; //Update <p> btn.innerText = `+1 and make it ${counter + 1}`; // Update <btn> }) import React, {useState} from “react”; export default function App() { const [counter, setCounter] = useState(0); return (<div> <p>{counter}</p> <button onClick={() => setCounter(counter++)}> `+1 and make it ${counter + 1}` </button> </div>) } //All elements depending on counter will update when counter changes value
  • 8. An Introduction To React For Frontend Developers hi@nakamurasei.com Why React? Virtual DOM In JavaScript one of the most performance degrading actions is updating the DOM, that is the elements that compose your webpage. As such, wouldn’t be great if we updated the DOM as less as possible? Enter the Virtual DOM. With React we have two versions of the DOM: the one that’s being displayed in the browser and an internal DOM that reflects the processed output by React. By comparing both DOMs we can update only the elements that we need. Without some technique like Virtual DOM we may need to update all the elements even if we modified only one, incurring a performance hit. 3
  • 9. An Introduction To React For Frontend Developers hi@nakamurasei.com Why React? Modular Structure In React, each part of the UI can be divided in smaller components. This makes coding more manageable and easier to work in a team, it allows the production of self-contained components that can be reused easily and since it’s JavaScript it allows data passing between components: no more storing data in the DOM and in humongous global states. 4
  • 10. An Introduction To React For Frontend Developers hi@nakamurasei.com Why React? Modular Structure Let’s see how components can make our code more manageable. 4 Vanilla JS React JS let fruits = [“mango”, “apple”, “banana”, “orange”]; const div = document.createElement(“div”); //Create <div> body.appendChild(div); //Append to body function addFruits() { fruits.forEach(fruit => { const p = document.createElement(“p”); p.innerText = fruit; div.appendChild(p);}) } addFruits(); import React, {useState, useEffect} from “react”; import Fruits from “./Fruits.js”; export default function App() { const [fruits, setFruits] = useState([“mango”, “apple”, “banana”, “orange”]); return (<Fruits fruits={fruits}/>); } import React, {useState, useEffect} from “react”; export default function Fruits(props) { return (<div>{props.fruits.map(fruit=><p key={fruit}>{fruit}</p>)}</div>); } //”fruits” was received from App() via props App.js Fruits.js
  • 11. An Introduction To React For Frontend Developers hi@nakamurasei.com React Basics You can build a React application with either classes or functions. While classes are useful when building complex components, in most cases using functions will be more readable and concise. You can build functional components in these ways. Note that we are exporting the function, so we can use it in another place. import React from “react”; export default function App() { return(<p>Hello World</p>); } import React from “react”; const App = () => { return(<p>Hello World</p>); } export default App;
  • 12. An Introduction To React For Frontend Developers hi@nakamurasei.com What you are seeing in orange isn’t HTML, is something called JSX, an extension of JavaScript used in React. When you are using JSX you are actually calling a function named “createElement” which outputs the HTML you are expecting. React Basics JSX import React from “react”; export default function App() { return(<p>Hello World</p>); }
  • 13. An Introduction To React For Frontend Developers hi@nakamurasei.com React Basics JSX JSX elements must be closed at all times. While most HTML elements follow the <></> structure, some elements don’t have an end tag (like <input> or <img>). In those cases you must add a / right before >, effectively closing it. <input type=”submit”> <input type=”submit”/> HTML React’s JSX
  • 14. An Introduction To React For Frontend Developers hi@nakamurasei.com React Basics JSX As we are seeing, JSX isn’t an exact copy of HTML. If you want to style your components using CSS, the “class” property isn’t allowed. Instead, use “className”. <p class=”hello”>Hello</p> <p className=”hello”>Hello</p> HTML React’s JSX
  • 15. An Introduction To React For Frontend Developers hi@nakamurasei.com React Basics JSX One of the advantages of JSX is that we can use JavaScript code instead of strings. To do so we wrap our code in {}. This allows us to use variables, render CSS class names conditionally, call functions and more. <p className=”hello”>{message}</p> //<p>’s content is the variable “message”. React’s JSX
  • 16. An Introduction To React For Frontend Developers hi@nakamurasei.com React Basics JSX - Using JS Code inside {} The code inside {} must always return something (even null). We can’t add more than one line (as in separate instructions divided by ;), however functions can have multiples lines inside it. <p className=”hello”>{ function renderStuff () { return “Hello” }; renderStuff()} </p> <p className=”hello”>{ “Hello” }</p> Invalid: Separate instructions OK
  • 17. An Introduction To React For Frontend Developers hi@nakamurasei.com React Basics JSX - Using JS Code inside {} We can’t use if as it doesn’t always return something. We can use a ternary expression instead, where the else clause returns null. <p className=”hello”>{ if(name === “Kentaro”){ return “You are Kentaro”} }</p> <p className=”hello”>{ name === “Kentaro” ? “You are Kentaro” : null }</p> Invalid: if OK
  • 18. An Introduction To React For Frontend Developers hi@nakamurasei.com React Basics JSX - Using JS Code inside {} To replace an if else clause use the ternary expression in the same way. <p className=”hello”>{ if(name === “Kentaro”){ return “You are Kentaro”} else { return “You are not Kentaro” } }</p> <p className=”hello”>{ name === “Kentaro” ? “You are Kentaro” : “You are not Kentaro” }</p> Invalid: if OK
  • 19. An Introduction To React For Frontend Developers hi@nakamurasei.com React Basics JSX - Using JS Code inside {} We can’t add loops (such as for or forEach). However we can use array’s map, since it will always return an array. <div>{ names.forEach(name => <p key={name}>{name}</p>)} </div> <div>{ names.map(name => <p key={name}>{name}</p>) }</div> Invalid: forEach <div>{ for(i = 0, n=names.length; i<n; i++){ return <p key={names[i]}>names[i]</p>} }</div> Invalid: for OK
  • 20. An Introduction To React For Frontend Developers hi@nakamurasei.com import React from “react”; import MyFunction from “./MyFunction.js”; const App = () => { return <MyFunction name=”Kentaro”/>; } export default App; App.js import React from “react”; const MyFunction = (props) => { return <p>{props.name}</p>; } export default MyFunction; MyFunction.js React Basics Modularity By splitting your application in several files code reuse and teamwork become easier. To import a component use “import” at the top of your file.
  • 21. An Introduction To React For Frontend Developers hi@nakamurasei.com React Basics Using state inside components To store information inside our components we can use “useState”, a React Hook (function that enables access to the state and lifecycle features of React.) import React, {useState} from “react”; import React, {useState} from “react”; export default function App() { const [counter, setCounter] = useState(0); return <p>{counter}</p>; } 1: Import useState at the top 2. Call useState inside the function
  • 22. An Introduction To React For Frontend Developers hi@nakamurasei.com React Basics Anatomy of useState const [counter, setCounter] = useState(0); 1: Pick a name for the variable that will hold the state’s value. 2: This is the function that will set the state’s value. By convention name it “set” + the name picked in 1 (camelCase). 3: This is the initial value of the state. Ideally set it to the same type as the expected value. For example, if you are expecting a number you can set it to 0. Functions, variables, even null and undefined is OK.
  • 23. An Introduction To React For Frontend Developers hi@nakamurasei.com React Basics useState example import React, {useState} from “react”; export default function App() { const [counter, setCounter] = useState(0); return (<div> <p>{counter}</p> <button onClick={() => setCounter(counter + 1)}>+1</button> </div> ) } 1: <p/> will hold the counter value. At initialization its value will be 0, as defined in useState. 2: When <button/> is clicked, the counter’s value will be incremented by 1. Automatically, every place that holds “counter” will update its value.
  • 24. An Introduction To React For Frontend Developers hi@nakamurasei.com React Basics useEffect Another React Hook is “useEffect”. Whatever instructions are inside of useEffect will get executed whenever there’s an update to its dependences. This lets us fetch data at component mount, execute functions when new information is received and more. import React, {useEffect} from “react”; import React, {useEffect} from “react”; export default function App() { useEffect(() => { //Place code here }, []); return <p>Hello world</p>; } 1: Import useEffect at the top 2. Call useEffect inside the function
  • 25. An Introduction To React For Frontend Developers hi@nakamurasei.com React Basics useEffect’s Behaviour The behaviour of useEffect changes depending on the dependencies defined in the [] at the end. useEffect(() => { //Place code here }, []); Component mount If nothing is defined inside [], the code inside useEffect will execute only once at component mount. This replaces React’s lifecycle method componentDidMount. useEffect(() => { //Place code here }, [varName]); Update at dependency change The code will execute once at component mount and everytime there’s a change of the dependencies defined inside []. You can add as many dependencies you wish.
  • 26. An Introduction To React For Frontend Developers hi@nakamurasei.com React Basics useEffect example import React, {useState, useEffect} from “react”; export default function App() { const [counter, setCounter] = useState(0); useEffect(()=>{ console.log(`Counter value is ${counter}`); }, [counter]); return (<div> <p>{counter}</p> <button onClick={() => setCounter(counter + 1)}>+1</button> </div> ) } Because “counter” is defined as a dependency of useEffect, it will console.log every time “counter” is incremented.
  • 27. Sergio Nakamura | nakamurasei.com hi@nakamurasei.com Thank you!
  翻译: