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!

More Related Content

What's hot

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 AngularJSTroy 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_servicekrishmdkk
 
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
 

What's hot (20)

Angular 8
Angular 8 Angular 8
Angular 8
 
Vaadin & Web Components
Vaadin & Web ComponentsVaadin & Web Components
Vaadin & Web Components
 
Vaadin Introduction, 7.3 edition
Vaadin Introduction, 7.3 editionVaadin Introduction, 7.3 edition
Vaadin Introduction, 7.3 edition
 
Beginning AngularJS
Beginning AngularJSBeginning AngularJS
Beginning AngularJS
 
Intoduction to Angularjs
Intoduction to AngularjsIntoduction to Angularjs
Intoduction to Angularjs
 
Adding User Management to Node.js
Adding User Management to Node.jsAdding User Management to Node.js
Adding User Management to Node.js
 
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
 
Web Components for Java Developers
Web Components for Java DevelopersWeb Components for Java Developers
Web Components for Java Developers
 
Flutter State Management Using GetX.pdf
Flutter State Management Using GetX.pdfFlutter State Management Using GetX.pdf
Flutter State Management Using GetX.pdf
 
Introduction to Vaadin
Introduction to VaadinIntroduction to Vaadin
Introduction to Vaadin
 
GWT Training - Session 1/3
GWT Training - Session 1/3GWT Training - Session 1/3
GWT Training - Session 1/3
 
Workshop: Building Vaadin add-ons
Workshop: Building Vaadin add-onsWorkshop: Building Vaadin add-ons
Workshop: Building Vaadin add-ons
 
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
 
React Js Simplified
React Js SimplifiedReact Js Simplified
React Js Simplified
 
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
 
JSLab. Алексей Волков. "React на практике"
JSLab. Алексей Волков. "React на практике"JSLab. Алексей Волков. "React на практике"
JSLab. Алексей Волков. "React на практике"
 
Angular JS2 Training Session #2
Angular JS2 Training Session #2Angular JS2 Training Session #2
Angular JS2 Training Session #2
 
Hackathon - Building vaadin add on components
Hackathon - Building vaadin add on componentsHackathon - Building vaadin add on components
Hackathon - Building vaadin add on components
 
An introduction to AngularJS
An introduction to AngularJSAn introduction to AngularJS
An introduction to AngularJS
 
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 ...
 

Similar to Introduction to React for Frontend Developers

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
 
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
 
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
 

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
 
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
 
React & Redux for noobs
React & Redux for noobsReact & Redux for noobs
React & Redux for noobs
 
REACT pdf.docx
REACT pdf.docxREACT pdf.docx
REACT pdf.docx
 
React JS: A Secret Preview
React JS: A Secret PreviewReact JS: A Secret Preview
React JS: A Secret Preview
 
Fundamental concepts of react js
Fundamental concepts of react jsFundamental concepts of react js
Fundamental concepts of react js
 
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
 
ReactJS.pptx
ReactJS.pptxReactJS.pptx
ReactJS.pptx
 
Tech Talk on ReactJS
Tech Talk on ReactJSTech Talk on ReactJS
Tech Talk on ReactJS
 
React outbox
React outboxReact outbox
React outbox
 
Build web apps with react js
Build web apps with react jsBuild web apps with react js
Build web apps with react js
 
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
 
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]
 
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
 
React Basic and Advance || React Basic
React Basic and Advance   || React BasicReact Basic and Advance   || React Basic
React Basic and Advance || React Basic
 
A full introductory guide to React
A full introductory guide to ReactA full introductory guide to React
A full introductory guide to React
 
Паразитируем на React-экосистеме (Angular 4+) / Алексей Охрименко (IPONWEB)
Паразитируем на React-экосистеме (Angular 4+) / Алексей Охрименко (IPONWEB)Паразитируем на React-экосистеме (Angular 4+) / Алексей Охрименко (IPONWEB)
Паразитируем на React-экосистеме (Angular 4+) / Алексей Охрименко (IPONWEB)
 
Building user interface with react
Building user interface with reactBuilding user interface with react
Building user interface with react
 
React Native +Redux + ES6 (Updated)
React Native +Redux + ES6 (Updated)React Native +Redux + ES6 (Updated)
React Native +Redux + ES6 (Updated)
 
Intro react js
Intro react jsIntro react js
Intro react js
 

Recently uploaded

一比一原版(LBS毕业证)伦敦商学院毕业证成绩单专业办理
一比一原版(LBS毕业证)伦敦商学院毕业证成绩单专业办理一比一原版(LBS毕业证)伦敦商学院毕业证成绩单专业办理
一比一原版(LBS毕业证)伦敦商学院毕业证成绩单专业办理
eutxy
 
[HUN][hackersuli] Red Teaming alapok 2024
[HUN][hackersuli] Red Teaming alapok 2024[HUN][hackersuli] Red Teaming alapok 2024
[HUN][hackersuli] Red Teaming alapok 2024
hackersuli
 
一比一原版(CSU毕业证)加利福尼亚州立大学毕业证成绩单专业办理
一比一原版(CSU毕业证)加利福尼亚州立大学毕业证成绩单专业办理一比一原版(CSU毕业证)加利福尼亚州立大学毕业证成绩单专业办理
一比一原版(CSU毕业证)加利福尼亚州立大学毕业证成绩单专业办理
ufdana
 
2.Cellular Networks_The final stage of connectivity is achieved by segmenting...
2.Cellular Networks_The final stage of connectivity is achieved by segmenting...2.Cellular Networks_The final stage of connectivity is achieved by segmenting...
2.Cellular Networks_The final stage of connectivity is achieved by segmenting...
JeyaPerumal1
 
7 Best Cloud Hosting Services to Try Out in 2024
7 Best Cloud Hosting Services to Try Out in 20247 Best Cloud Hosting Services to Try Out in 2024
7 Best Cloud Hosting Services to Try Out in 2024
Danica Gill
 
重新申请毕业证书(RMIT毕业证)皇家墨尔本理工大学毕业证成绩单精仿办理
重新申请毕业证书(RMIT毕业证)皇家墨尔本理工大学毕业证成绩单精仿办理重新申请毕业证书(RMIT毕业证)皇家墨尔本理工大学毕业证成绩单精仿办理
重新申请毕业证书(RMIT毕业证)皇家墨尔本理工大学毕业证成绩单精仿办理
vmemo1
 
急速办(bedfordhire毕业证书)英国贝德福特大学毕业证成绩单原版一模一样
急速办(bedfordhire毕业证书)英国贝德福特大学毕业证成绩单原版一模一样急速办(bedfordhire毕业证书)英国贝德福特大学毕业证成绩单原版一模一样
急速办(bedfordhire毕业证书)英国贝德福特大学毕业证成绩单原版一模一样
3ipehhoa
 
test test test test testtest test testtest test testtest test testtest test ...
test test  test test testtest test testtest test testtest test testtest test ...test test  test test testtest test testtest test testtest test testtest test ...
test test test test testtest test testtest test testtest test testtest test ...
Arif0071
 
原版仿制(uob毕业证书)英国伯明翰大学毕业证本科学历证书原版一模一样
原版仿制(uob毕业证书)英国伯明翰大学毕业证本科学历证书原版一模一样原版仿制(uob毕业证书)英国伯明翰大学毕业证本科学历证书原版一模一样
原版仿制(uob毕业证书)英国伯明翰大学毕业证本科学历证书原版一模一样
3ipehhoa
 
JAVIER LASA-EXPERIENCIA digital 1986-2024.pdf
JAVIER LASA-EXPERIENCIA digital 1986-2024.pdfJAVIER LASA-EXPERIENCIA digital 1986-2024.pdf
JAVIER LASA-EXPERIENCIA digital 1986-2024.pdf
Javier Lasa
 
Explore-Insanony: Watch Instagram Stories Secretly
Explore-Insanony: Watch Instagram Stories SecretlyExplore-Insanony: Watch Instagram Stories Secretly
Explore-Insanony: Watch Instagram Stories Secretly
Trending Blogers
 
Bridging the Digital Gap Brad Spiegel Macon, GA Initiative.pptx
Bridging the Digital Gap Brad Spiegel Macon, GA Initiative.pptxBridging the Digital Gap Brad Spiegel Macon, GA Initiative.pptx
Bridging the Digital Gap Brad Spiegel Macon, GA Initiative.pptx
Brad Spiegel Macon GA
 
假文凭国外(Adelaide毕业证)澳大利亚国立大学毕业证成绩单办理
假文凭国外(Adelaide毕业证)澳大利亚国立大学毕业证成绩单办理假文凭国外(Adelaide毕业证)澳大利亚国立大学毕业证成绩单办理
假文凭国外(Adelaide毕业证)澳大利亚国立大学毕业证成绩单办理
cuobya
 
制作毕业证书(ANU毕业证)莫纳什大学毕业证成绩单官方原版办理
制作毕业证书(ANU毕业证)莫纳什大学毕业证成绩单官方原版办理制作毕业证书(ANU毕业证)莫纳什大学毕业证成绩单官方原版办理
制作毕业证书(ANU毕业证)莫纳什大学毕业证成绩单官方原版办理
cuobya
 
可查真实(Monash毕业证)西澳大学毕业证成绩单退学买
可查真实(Monash毕业证)西澳大学毕业证成绩单退学买可查真实(Monash毕业证)西澳大学毕业证成绩单退学买
可查真实(Monash毕业证)西澳大学毕业证成绩单退学买
cuobya
 
Internet of Things in Manufacturing: Revolutionizing Efficiency & Quality | C...
Internet of Things in Manufacturing: Revolutionizing Efficiency & Quality | C...Internet of Things in Manufacturing: Revolutionizing Efficiency & Quality | C...
Internet of Things in Manufacturing: Revolutionizing Efficiency & Quality | C...
CIOWomenMagazine
 
APNIC Foundation, presented by Ellisha Heppner at the PNG DNS Forum 2024
APNIC Foundation, presented by Ellisha Heppner at the PNG DNS Forum 2024APNIC Foundation, presented by Ellisha Heppner at the PNG DNS Forum 2024
APNIC Foundation, presented by Ellisha Heppner at the PNG DNS Forum 2024
APNIC
 
Gen Z and the marketplaces - let's translate their needs
Gen Z and the marketplaces - let's translate their needsGen Z and the marketplaces - let's translate their needs
Gen Z and the marketplaces - let's translate their needs
Laura Szabó
 
Italy Agriculture Equipment Market Outlook to 2027
Italy Agriculture Equipment Market Outlook to 2027Italy Agriculture Equipment Market Outlook to 2027
Italy Agriculture Equipment Market Outlook to 2027
harveenkaur52
 
Understanding User Behavior with Google Analytics.pdf
Understanding User Behavior with Google Analytics.pdfUnderstanding User Behavior with Google Analytics.pdf
Understanding User Behavior with Google Analytics.pdf
SEO Article Boost
 

Recently uploaded (20)

一比一原版(LBS毕业证)伦敦商学院毕业证成绩单专业办理
一比一原版(LBS毕业证)伦敦商学院毕业证成绩单专业办理一比一原版(LBS毕业证)伦敦商学院毕业证成绩单专业办理
一比一原版(LBS毕业证)伦敦商学院毕业证成绩单专业办理
 
[HUN][hackersuli] Red Teaming alapok 2024
[HUN][hackersuli] Red Teaming alapok 2024[HUN][hackersuli] Red Teaming alapok 2024
[HUN][hackersuli] Red Teaming alapok 2024
 
一比一原版(CSU毕业证)加利福尼亚州立大学毕业证成绩单专业办理
一比一原版(CSU毕业证)加利福尼亚州立大学毕业证成绩单专业办理一比一原版(CSU毕业证)加利福尼亚州立大学毕业证成绩单专业办理
一比一原版(CSU毕业证)加利福尼亚州立大学毕业证成绩单专业办理
 
2.Cellular Networks_The final stage of connectivity is achieved by segmenting...
2.Cellular Networks_The final stage of connectivity is achieved by segmenting...2.Cellular Networks_The final stage of connectivity is achieved by segmenting...
2.Cellular Networks_The final stage of connectivity is achieved by segmenting...
 
7 Best Cloud Hosting Services to Try Out in 2024
7 Best Cloud Hosting Services to Try Out in 20247 Best Cloud Hosting Services to Try Out in 2024
7 Best Cloud Hosting Services to Try Out in 2024
 
重新申请毕业证书(RMIT毕业证)皇家墨尔本理工大学毕业证成绩单精仿办理
重新申请毕业证书(RMIT毕业证)皇家墨尔本理工大学毕业证成绩单精仿办理重新申请毕业证书(RMIT毕业证)皇家墨尔本理工大学毕业证成绩单精仿办理
重新申请毕业证书(RMIT毕业证)皇家墨尔本理工大学毕业证成绩单精仿办理
 
急速办(bedfordhire毕业证书)英国贝德福特大学毕业证成绩单原版一模一样
急速办(bedfordhire毕业证书)英国贝德福特大学毕业证成绩单原版一模一样急速办(bedfordhire毕业证书)英国贝德福特大学毕业证成绩单原版一模一样
急速办(bedfordhire毕业证书)英国贝德福特大学毕业证成绩单原版一模一样
 
test test test test testtest test testtest test testtest test testtest test ...
test test  test test testtest test testtest test testtest test testtest test ...test test  test test testtest test testtest test testtest test testtest test ...
test test test test testtest test testtest test testtest test testtest test ...
 
原版仿制(uob毕业证书)英国伯明翰大学毕业证本科学历证书原版一模一样
原版仿制(uob毕业证书)英国伯明翰大学毕业证本科学历证书原版一模一样原版仿制(uob毕业证书)英国伯明翰大学毕业证本科学历证书原版一模一样
原版仿制(uob毕业证书)英国伯明翰大学毕业证本科学历证书原版一模一样
 
JAVIER LASA-EXPERIENCIA digital 1986-2024.pdf
JAVIER LASA-EXPERIENCIA digital 1986-2024.pdfJAVIER LASA-EXPERIENCIA digital 1986-2024.pdf
JAVIER LASA-EXPERIENCIA digital 1986-2024.pdf
 
Explore-Insanony: Watch Instagram Stories Secretly
Explore-Insanony: Watch Instagram Stories SecretlyExplore-Insanony: Watch Instagram Stories Secretly
Explore-Insanony: Watch Instagram Stories Secretly
 
Bridging the Digital Gap Brad Spiegel Macon, GA Initiative.pptx
Bridging the Digital Gap Brad Spiegel Macon, GA Initiative.pptxBridging the Digital Gap Brad Spiegel Macon, GA Initiative.pptx
Bridging the Digital Gap Brad Spiegel Macon, GA Initiative.pptx
 
假文凭国外(Adelaide毕业证)澳大利亚国立大学毕业证成绩单办理
假文凭国外(Adelaide毕业证)澳大利亚国立大学毕业证成绩单办理假文凭国外(Adelaide毕业证)澳大利亚国立大学毕业证成绩单办理
假文凭国外(Adelaide毕业证)澳大利亚国立大学毕业证成绩单办理
 
制作毕业证书(ANU毕业证)莫纳什大学毕业证成绩单官方原版办理
制作毕业证书(ANU毕业证)莫纳什大学毕业证成绩单官方原版办理制作毕业证书(ANU毕业证)莫纳什大学毕业证成绩单官方原版办理
制作毕业证书(ANU毕业证)莫纳什大学毕业证成绩单官方原版办理
 
可查真实(Monash毕业证)西澳大学毕业证成绩单退学买
可查真实(Monash毕业证)西澳大学毕业证成绩单退学买可查真实(Monash毕业证)西澳大学毕业证成绩单退学买
可查真实(Monash毕业证)西澳大学毕业证成绩单退学买
 
Internet of Things in Manufacturing: Revolutionizing Efficiency & Quality | C...
Internet of Things in Manufacturing: Revolutionizing Efficiency & Quality | C...Internet of Things in Manufacturing: Revolutionizing Efficiency & Quality | C...
Internet of Things in Manufacturing: Revolutionizing Efficiency & Quality | C...
 
APNIC Foundation, presented by Ellisha Heppner at the PNG DNS Forum 2024
APNIC Foundation, presented by Ellisha Heppner at the PNG DNS Forum 2024APNIC Foundation, presented by Ellisha Heppner at the PNG DNS Forum 2024
APNIC Foundation, presented by Ellisha Heppner at the PNG DNS Forum 2024
 
Gen Z and the marketplaces - let's translate their needs
Gen Z and the marketplaces - let's translate their needsGen Z and the marketplaces - let's translate their needs
Gen Z and the marketplaces - let's translate their needs
 
Italy Agriculture Equipment Market Outlook to 2027
Italy Agriculture Equipment Market Outlook to 2027Italy Agriculture Equipment Market Outlook to 2027
Italy Agriculture Equipment Market Outlook to 2027
 
Understanding User Behavior with Google Analytics.pdf
Understanding User Behavior with Google Analytics.pdfUnderstanding User Behavior with Google Analytics.pdf
Understanding User Behavior with Google Analytics.pdf
 

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!