SlideShare a Scribd company logo
1 of 21
Download to read offline
How To React
Aspetti avanzati della gestione dello stato applicativo
Aldo Noschese x Riccardo Tartaglia
#howToReact
Aldo Noschese
Front-end Dev @ weBeetle
Riccardo Tartaglia
Full-Stack Dev @ weBeetle
@noschese_aldo
aldo-noschese-5b9101193
@riktarweb
riccardo-tartaglia
❏ Basi di React.js
❏ Virtual DOM
❏ JSX & Componenti
❏ Built-In Hooks
#howToReact
Today
Previous
❏ Custom Hooks
❏ Ui State VS Server State
❏ Global State with Recoil.js
❏ Server State with React Query
Basic Hooks:
useState();
useEffect();
useContext();
Additional Hooks:
useReducer();
useCallback();
useMemo();
useRef();
useImperativeHandle();
useLayoutEffect();
useDebugValue();
Built-In Hooks
React dalla versione 16.8, introduce il
concetto di “Hooks”.
Gli hooks ci permettono di utilizzare
lo stato ed altre funzionalità senza
dover scrivere una classe.
Alcune regole:
● Non utilizzare gli hooks
all’interno di normali funzioni
JavaScript
● Non utilizzare gli hooks
all’interno di condizioni o
cicli.
#howToReact
const useCounter = () => {
const [counter , setCounter] = useState(0);
const increment = (num) => {
setCounter(prev => prev + num)
};
const decrement = (num) => {
setCounter(prev => prev - num)
};
return {
counter,
increment,
decrement
}
};
Custom Hooks
Come abbiamo visto, React ci consente
di utilizzare diversi hooks, che ci
vengono forniti direttamente insieme
alla libreria.
I custom hooks in React,invece, ci
consentono di astrarre logica dai
nostri componenti ed inserirla in
funzioni riutilizzabili, poi,
all’interno della nostra applicazione.
#howToReact
#howToReact
Live Coding
Stato Applicativo
Di cosa si tratta ?
I componenti spesso devono cambiare ciò che appare sullo schermo a seguito di un’interazione da parte
dell’utente, ad esempio, al click di un bottone deve cambiare il tema da “light” a “dark”, o se
l’utente sta scrivendo all’interno di un campo di input, deve ricordarne il valore, o se clicca il
pulsante “avanti” nelle slides di un carosello, la slide da visualizzare deve cambiare.
I componenti devono essere in grado di “ricordare” tutte queste cose, in React questo tipo di memoria
viene chiamata State, stato applicativo.
#howToReact
#howToReact
Layers di stato
Stato
UI State Server State
Ui State
Cos’è ?
Quando parliamo di ui state, facciamo riferimento ad una o più porzioni di stato applicativo dedite
alla gestione degli elementi presenti in interfaccia.
#howToReact
#howToReact
Ui State Layers
Ui State
Local Global
Ui State: Local Layer
Un esempio di stato locale è la
gestione di una conta.
Un componente istanzia una variabile di
stato, gestisce le operazioni relative
a quest’ultimo, ed eventualmente lo
condivide ai suoi componenti figli.
Una variabile di stato locale non è
visibile a componenti esterni, a meno
che non venga condivisa esplicitamente
con la Props Drilling o implicitamente
attraverso un Context.
#howToReact
const Counter = () => {
const [counter , setCounter] = useState(0)
return <span>Counter : {counter}</span>
};
Ui State: Global Layer
Un esempio di stato globale è la
gestione del tema applicativo.
Uno stato deve essere trattato come
globale, solo quando l’intera
applicazione ha la necessità di
attingere da quella porzione di stato.
Una variabile di stato globale, sarà
quindi, visibile da tutti i componenti
dell’applicazione, che ne faranno uso
per essere in grado di svolgere il loro
compito correttamente.
#howToReact
const App = () => {
const [theme , setTheme] = useState(“dark”)
return (
<>
<ChildOne theme={theme} />
<ChildTwo theme={theme} />
</>
)
};
const ChildOne = (props) => {
const {theme} = props
return <Text color={theme}>Hello</Text>
};
const ChildTwo = (props) => {
const {theme} = props
return <Text color={theme}>Hello</Text>
};
export const counterAtom = atom({
key:”counterAtom”,
default:0
});
Recoil.Js: A state manager for React
Recoil.js è una libreria per la
gestione dello stato applicativo in
React.js.
Ci aiuta a gestire la nostra porzione
di stato applicativo globale, creando
un flusso di dati che parte dagli atomi
ed arriva direttamente ai componenti
che ne necessitano.
#howToReact
const Counter = () => {
const [counter , setCounter] =
useRecoilState(counterAtom)
return <span>Counter : {counter}</span>
};
#howToReact
Live Coding
Server State
Cos’è ?
Quando parliamo di Server State, facciamo riferimento ad una o più porzioni di stato applicativo
dedicate alla gestione dei dati che il server ci fornisce nel momento in cui effettuiamo delle chiamate
API verso di esso.
#howToReact
const getPokemons = async () => {
const {data} = await axios.get(“/pokemons”);
return data;
};
Server State
React ci fornisce delle soluzioni per
gestire il nostro UI State, ma non ci
fornisce alcuno strumento per gestire
il Server State.
Per questo motivo sta a noi decidere
dove e come gestire questo layer di
stato.
#howToReact
//…some code
const retrievePokemons = async () => {
const pokemons = await getPokemons();
setPokemons(pokemons);
}
useEffect(() => {
retrievePokemons();
} ,[])
//…more code
React Query
Esistono varie soluzioni per gestire al
meglio il nostro Server State, tra
queste, una libreria molto interessante
è React Query.
React Query ci aiuta a gestire:
● Fetching
● Incremental Fetching
● Pre-fetching
● Caching
#howToReact
const {data, isLoading, isError} =
useQuery([“pokemons”], async () => getPokemons())
const getPokemons = async () => {
const {data} = await axios.get(“/pokemons”);
return data;
};
#howToReact
Live Coding
Mettiamo insieme i pezzi…
#howToReact
#howToReact
Live Coding
Aldo Noschese x Riccardo Tartaglia
thank.u!
see u next time

More Related Content

Similar to How To React - Aspetti avanzati della gestione dello stato

April 2010 - Seam unifies JEE5
April 2010 - Seam unifies JEE5April 2010 - Seam unifies JEE5
April 2010 - Seam unifies JEE5JBug Italy
 
Asp.net 4 Community Tour VS2010
Asp.net 4 Community Tour VS2010Asp.net 4 Community Tour VS2010
Asp.net 4 Community Tour VS2010Fabrizio Bernabei
 
Asp.Net MVC 3 - Il Model View Controller secondo Microsoft
Asp.Net MVC 3 - Il Model View Controller secondo MicrosoftAsp.Net MVC 3 - Il Model View Controller secondo Microsoft
Asp.Net MVC 3 - Il Model View Controller secondo MicrosoftStefano Benedetti
 
Entity Framework 4 vs NHibernate 3
Entity Framework 4 vs NHibernate 3Entity Framework 4 vs NHibernate 3
Entity Framework 4 vs NHibernate 3Martino Bordin
 
Web Api – The HTTP Way
Web Api – The HTTP WayWeb Api – The HTTP Way
Web Api – The HTTP WayLuca Milan
 
How create a single page apps using html5 and javascript
How create a single page apps using html5 and javascript How create a single page apps using html5 and javascript
How create a single page apps using html5 and javascript Stefano Marchisio
 
04 Tapestry5 In Action Pratica
04   Tapestry5 In Action   Pratica04   Tapestry5 In Action   Pratica
04 Tapestry5 In Action Praticabobpuley
 
Introduzione a Node.js
Introduzione a Node.jsIntroduzione a Node.js
Introduzione a Node.jsMichele Capra
 
Niccolò Becchi: Introduzione a GWT
Niccolò Becchi: Introduzione a GWTNiccolò Becchi: Introduzione a GWT
Niccolò Becchi: Introduzione a GWTfirenze-gtug
 
02 Struts Actions3016
02 Struts Actions301602 Struts Actions3016
02 Struts Actions3016DavideBos
 
02 Struts Actions3016
02 Struts Actions301602 Struts Actions3016
02 Struts Actions3016DavideBos
 

Similar to How To React - Aspetti avanzati della gestione dello stato (20)

April 2010 - Seam unifies JEE5
April 2010 - Seam unifies JEE5April 2010 - Seam unifies JEE5
April 2010 - Seam unifies JEE5
 
react-it.pdf
react-it.pdfreact-it.pdf
react-it.pdf
 
Asp.net 4 Community Tour VS2010
Asp.net 4 Community Tour VS2010Asp.net 4 Community Tour VS2010
Asp.net 4 Community Tour VS2010
 
Notes for an Enterprise Scheduling Distributed Application
Notes for an Enterprise Scheduling Distributed ApplicationNotes for an Enterprise Scheduling Distributed Application
Notes for an Enterprise Scheduling Distributed Application
 
Novità di Asp.Net 4.0
Novità di Asp.Net 4.0Novità di Asp.Net 4.0
Novità di Asp.Net 4.0
 
Asp.Net MVC 3 - Il Model View Controller secondo Microsoft
Asp.Net MVC 3 - Il Model View Controller secondo MicrosoftAsp.Net MVC 3 - Il Model View Controller secondo Microsoft
Asp.Net MVC 3 - Il Model View Controller secondo Microsoft
 
Entity Framework 4 vs NHibernate 3
Entity Framework 4 vs NHibernate 3Entity Framework 4 vs NHibernate 3
Entity Framework 4 vs NHibernate 3
 
Web Api – The HTTP Way
Web Api – The HTTP WayWeb Api – The HTTP Way
Web Api – The HTTP Way
 
AngularJS-Intro
AngularJS-IntroAngularJS-Intro
AngularJS-Intro
 
MVC and Struts 1
MVC and Struts 1MVC and Struts 1
MVC and Struts 1
 
How create a single page apps using html5 and javascript
How create a single page apps using html5 and javascript How create a single page apps using html5 and javascript
How create a single page apps using html5 and javascript
 
Rx - ReactiveX
Rx - ReactiveXRx - ReactiveX
Rx - ReactiveX
 
04 Tapestry5 In Action Pratica
04   Tapestry5 In Action   Pratica04   Tapestry5 In Action   Pratica
04 Tapestry5 In Action Pratica
 
Introduzione a node.js
Introduzione a node.jsIntroduzione a node.js
Introduzione a node.js
 
Introduzione a Node.js
Introduzione a Node.jsIntroduzione a Node.js
Introduzione a Node.js
 
Niccolò Becchi: Introduzione a GWT
Niccolò Becchi: Introduzione a GWTNiccolò Becchi: Introduzione a GWT
Niccolò Becchi: Introduzione a GWT
 
02 Struts Actions3016
02 Struts Actions301602 Struts Actions3016
02 Struts Actions3016
 
02 Struts Actions3016
02 Struts Actions301602 Struts Actions3016
02 Struts Actions3016
 
02 Struts Actions
02  Struts  Actions02  Struts  Actions
02 Struts Actions
 
Il web 2.0
Il web 2.0Il web 2.0
Il web 2.0
 

How To React - Aspetti avanzati della gestione dello stato

  • 1. How To React Aspetti avanzati della gestione dello stato applicativo Aldo Noschese x Riccardo Tartaglia
  • 2. #howToReact Aldo Noschese Front-end Dev @ weBeetle Riccardo Tartaglia Full-Stack Dev @ weBeetle @noschese_aldo aldo-noschese-5b9101193 @riktarweb riccardo-tartaglia
  • 3. ❏ Basi di React.js ❏ Virtual DOM ❏ JSX & Componenti ❏ Built-In Hooks #howToReact Today Previous ❏ Custom Hooks ❏ Ui State VS Server State ❏ Global State with Recoil.js ❏ Server State with React Query
  • 4. Basic Hooks: useState(); useEffect(); useContext(); Additional Hooks: useReducer(); useCallback(); useMemo(); useRef(); useImperativeHandle(); useLayoutEffect(); useDebugValue(); Built-In Hooks React dalla versione 16.8, introduce il concetto di “Hooks”. Gli hooks ci permettono di utilizzare lo stato ed altre funzionalità senza dover scrivere una classe. Alcune regole: ● Non utilizzare gli hooks all’interno di normali funzioni JavaScript ● Non utilizzare gli hooks all’interno di condizioni o cicli. #howToReact
  • 5. const useCounter = () => { const [counter , setCounter] = useState(0); const increment = (num) => { setCounter(prev => prev + num) }; const decrement = (num) => { setCounter(prev => prev - num) }; return { counter, increment, decrement } }; Custom Hooks Come abbiamo visto, React ci consente di utilizzare diversi hooks, che ci vengono forniti direttamente insieme alla libreria. I custom hooks in React,invece, ci consentono di astrarre logica dai nostri componenti ed inserirla in funzioni riutilizzabili, poi, all’interno della nostra applicazione. #howToReact
  • 7. Stato Applicativo Di cosa si tratta ? I componenti spesso devono cambiare ciò che appare sullo schermo a seguito di un’interazione da parte dell’utente, ad esempio, al click di un bottone deve cambiare il tema da “light” a “dark”, o se l’utente sta scrivendo all’interno di un campo di input, deve ricordarne il valore, o se clicca il pulsante “avanti” nelle slides di un carosello, la slide da visualizzare deve cambiare. I componenti devono essere in grado di “ricordare” tutte queste cose, in React questo tipo di memoria viene chiamata State, stato applicativo. #howToReact
  • 9. Ui State Cos’è ? Quando parliamo di ui state, facciamo riferimento ad una o più porzioni di stato applicativo dedite alla gestione degli elementi presenti in interfaccia. #howToReact
  • 10. #howToReact Ui State Layers Ui State Local Global
  • 11. Ui State: Local Layer Un esempio di stato locale è la gestione di una conta. Un componente istanzia una variabile di stato, gestisce le operazioni relative a quest’ultimo, ed eventualmente lo condivide ai suoi componenti figli. Una variabile di stato locale non è visibile a componenti esterni, a meno che non venga condivisa esplicitamente con la Props Drilling o implicitamente attraverso un Context. #howToReact const Counter = () => { const [counter , setCounter] = useState(0) return <span>Counter : {counter}</span> };
  • 12. Ui State: Global Layer Un esempio di stato globale è la gestione del tema applicativo. Uno stato deve essere trattato come globale, solo quando l’intera applicazione ha la necessità di attingere da quella porzione di stato. Una variabile di stato globale, sarà quindi, visibile da tutti i componenti dell’applicazione, che ne faranno uso per essere in grado di svolgere il loro compito correttamente. #howToReact const App = () => { const [theme , setTheme] = useState(“dark”) return ( <> <ChildOne theme={theme} /> <ChildTwo theme={theme} /> </> ) }; const ChildOne = (props) => { const {theme} = props return <Text color={theme}>Hello</Text> }; const ChildTwo = (props) => { const {theme} = props return <Text color={theme}>Hello</Text> };
  • 13. export const counterAtom = atom({ key:”counterAtom”, default:0 }); Recoil.Js: A state manager for React Recoil.js è una libreria per la gestione dello stato applicativo in React.js. Ci aiuta a gestire la nostra porzione di stato applicativo globale, creando un flusso di dati che parte dagli atomi ed arriva direttamente ai componenti che ne necessitano. #howToReact const Counter = () => { const [counter , setCounter] = useRecoilState(counterAtom) return <span>Counter : {counter}</span> };
  • 15. Server State Cos’è ? Quando parliamo di Server State, facciamo riferimento ad una o più porzioni di stato applicativo dedicate alla gestione dei dati che il server ci fornisce nel momento in cui effettuiamo delle chiamate API verso di esso. #howToReact
  • 16. const getPokemons = async () => { const {data} = await axios.get(“/pokemons”); return data; }; Server State React ci fornisce delle soluzioni per gestire il nostro UI State, ma non ci fornisce alcuno strumento per gestire il Server State. Per questo motivo sta a noi decidere dove e come gestire questo layer di stato. #howToReact //…some code const retrievePokemons = async () => { const pokemons = await getPokemons(); setPokemons(pokemons); } useEffect(() => { retrievePokemons(); } ,[]) //…more code
  • 17. React Query Esistono varie soluzioni per gestire al meglio il nostro Server State, tra queste, una libreria molto interessante è React Query. React Query ci aiuta a gestire: ● Fetching ● Incremental Fetching ● Pre-fetching ● Caching #howToReact const {data, isLoading, isError} = useQuery([“pokemons”], async () => getPokemons()) const getPokemons = async () => { const {data} = await axios.get(“/pokemons”); return data; };
  • 19. Mettiamo insieme i pezzi… #howToReact
  • 21. Aldo Noschese x Riccardo Tartaglia thank.u! see u next time