useEffect Hook In React / Load and Save State from LocalStorage: The 10 Days of React JS (Day 10)

by birtanpublished on July 3, 2020

[Music]

hello everyone in this lesson we're

going to put the finishing touches on

our simple example application and we're

also going to learn about a tool and

react named use effect let's get started

by adding a delete button next to each

of the pets in our list so to add that

button let's find our pet component for

me it's around line number 79 or 80 but

it's probably a bit different for you

but we're just looking for the function

named upper case pet and right before

the closing list item tag we just want

to add a button here now you don't need

to do this but because my screen is

really zoomed in and I can't fit much on

the screen at once I'm actually going to

wrap this bit of JSX in parentheses so

that I can drop down and I'm really only

doing this so that before the closing

list tag I can drop down to add the

button element here and this way it will

fit all on one line on the screen so

it's easier for you to see and follow

along with me okay within this button

let's have a bit of text that says

delete and then what do we want to do

when the user clicks on this button well

let's add a prop named on click equals

curly brackets and then we can make up a

name for a function so we haven't

created this function yet but we will in

just a few seconds let's say candle

delete okay now within this overall pet

function we just need to create a

function with this name so let's say

function candle delete parentheses curly

brackets okay and now within this

function this is where we need to stop

and actually think about what we're

trying to accomplish so what we need to

do is determine the ID of the pet that

we just clicked delete on and then we

want to go into the state of all of our

pets find the item that has that

matching ID and remove it from the array

so let me show you how I would do that

before we actually work on this handle

delete function let's go up to our

overall our app component all right so

it's towards the top function our app

and let's look at the JSX right the our

header area the like area and then we

have this

ordered lists where we're looping

through the pets and then here we see

the uppercase pet component well let's

add a few props to it

so after uppercase pet let's say ID

equals curly brackets and let's just

give it pet ID okay and then we need to

realize that we want to be able to

update the state of our pets from within

the pet component and remember that

state of all of our pets actually lives

in the our app component not the pet

component so while we're here let's also

add one more prop named set pets and set

it to equal curly brackets set pets

right this is that react function that

lets us change the state or update the

state okay with both of these props in

place let's go back down to our pet

component okay and now we can actually

work on our handle delete function so

here's what we want to do we want to

call the props dot set pets function

right because we want to change the

state we want to remove an item from

that array of pets in state so within

these parentheses it's our job to give

it a new array with all of the pets

except for the one that we just want to

get rid of now that means we're going to

need to work with the previous state

value so let's give this an arrow

function

there's the previous state arrow symbol

so let's start working with the array of

pets or the previous state and again we

don't want to call any methods on this

array that would mutate it or directly

change it so instead we can call a

method named filter filter has nothing

to do with react it's just a part of

JavaScript so every array in JavaScript

has access to filter and it will return

a brand-new array how it works is you

give it a function and it's going to run

that function once for each item in the

array now in that function if you return

a value of true that current item you've

looped to will be included in the new

array that filter is generating if you

return a value of false it will be

skipped so all we really need to do is

provide a function that returns true

unless the ID of the pet matches the ID

of the pet button that we just clicked

on within the filter parentheses let's

say pet to work with the pet that we've

looped to we're just creating an es6

arrow function and we're just going to

return true if pet dot ID does not equal

the ID of the pet that just got clicked

on so to access that idea would be props

dot ID and that's it that's all we need

to do react will take care of everything

else

so let's test this out let's come down

to our list maybe I want to get rid of

fluffy the rabbit click delete perfect

or if I add a new pet test cat age of

six years old that gets added but if I

want to remove it just click delete

okay so we've completed our delete

feature at this point let's change gears

and set things up so that when the page

gets reloaded we don't lose our data I'm

sure you've noticed that anytime you

change your code and code panic reloads

the preview area and in our case that

means we lose any data we've manipulated

now this idea of persistent data in the

web browser has nothing to do with react

and everything to do with just the

nature of web browsers but that doesn't

matter this is still the perfect excuse

to learn about something in react named

use effect so let's do this let's go up

into our code towards the top within our

main our app component and let's make it

so that when you first visit the page

none of these pre-existing or hard-coded

pets exist we really only ever added

these pets as an example so we had

something to work with but now that we

have a form that you can fill out to add

pets we don't need these anymore so when

we're saying use state and then we have

square brackets and then these items

just delete all of the items and then

get rid of the empty space just like

this so that it says pets you state and

then it's just an empty array right an

empty pair of square brackets so now

down in our preview obviously there are

no pets to see and now when

one adds a pet to the forum not only do

we want to add that new pet to stay but

we want to somehow persist that data in

the web browser so that even if you

reload the page that data still exists

now even though that's more about web

browsers and less about react let me

show you how we will achieve this within

the context of react so maybe right

below this line when we're setting our

pets state let's add two comments for

ourselves just to stay organized so /

slashed out of comment and let's say

only run once the first time this

component is rendered okay and then

below that let's add one more comment

and say run every time our pet state

changes so here's what we're going to do

we're going to leverage the web browsers

local storage feature local storage has

nothing to do with react but it's how we

can have persistent data within a web

browser so the very first time our

component is rendered we're going to

load any existing data from local

storage loaded in the state but then we

also want to save our latest data back

into the browser's local storage so

anytime our pet data changes we're going

to save our pet state back into the

browser's local storage now this whole

situation of needing to do something

during a certain circumstance like this

this is where use effect comes into play

so let me show you what we're going to

do for this first situation we can say

use effect now I should point out that

just like we needed to include or create

this shortcut name to use State we need

to do the same thing for use effect so

up at the very top of our code let's add

a new line and say Const use effect

equals uppercase react dot use effect

okay so now we can actually access it by

just typing use effect

okay so we're actually using it here and

we want to give use effect to things so

we could say a comma B while we're at it

why don't we also go ahead and you

the same code under this comment right

when we want to do something every time

our pet data state changes so use effect

a comma B now the first argument is a

function that you want to run and the

second argument is where you list the

dependencies or the things that you want

to watch for changes and then only when

react detects that those things have

changed only then will it actually call

your function so let's focus on this

example first we only want this function

here to run the very first time that

this component is rendered now to do

that instead of this B placeholder for

the second argument we just provide an

empty array now down in this example we

want this function to run every time our

pet state changes so instead of this B

placeholder we would have an array and

the only item in that array that we want

to watch for is our pets state now in

case I didn't make it clear before this

moment by default any code that lives

within a component function is going to

run every time that component gets

rear-ended so use effect is our way of

including code within our component but

only actually running it at the specific

times that we want to run it okay at

this point let's focus on the function

that we want to run only the first time

that the component is rendered so

instead of a placeholder we can include

an aero function so empty set of

parentheses and then the arrow symbol

curly brackets and then inside those

drop down okay and actually before we

write what we want to do here why don't

we also add an arrow function for this

second use effect so instead of that a

placeholder empty set of parentheses

arrow symbol curly brackets I think it

actually makes more sense to begin with

this function that we want to run every

time our pet state changes so if the pet

data changes we would want to save it to

the web browsers local storage so write

this out with me within this second use

effect let's say local storage this is

just a universal web browser feature

dot set item so every modern web browser

has access to this feature and we give

this to arguments so a comma B the first

argument is a name that you make up for

this piece of data that the browser is

going to store so instead of a why don't

we call it quotes maybe example pet data

okay and then instead of the second

argument or the placeholder B we would

just want to store our pets data however

our pets data is an array

whereas local storage in the browser

only accepts a simple string of text not

actual code or data so to get around

this here's what we can do we can say

JSON

that's all uppercase JSON dot stringify

parentheses to call that and then just

include our state right or our data

lowercase pets so this is a web browser

feature that will turn our data into a

string of text and then we're saving it

in local storage cool so now react will

take care of running this each and every

time our pet state changes now within

this use effect we only want to run this

when the component is first rendered and

this is where we would want to load any

data from the web browsers local storage

if it exists so this is where we would

say if parentheses curly brackets for

the condition we would say only if local

storage dot gift item parentheses

only if example pet data only if it

actually exists then we would want to

load it so within these curly brackets

we could drop down and say set pets

right this is the function that lets us

update our state within the component

okay and then before we actually pull in

the data from the browser's local

storage we would first want to parse it

because remember what's stored in the

web browser is just a string of text but

we want to parse it so that it's actual

JavaScript data so that it's actually an

array of objects so to do that we just

say uppercase JSON dot parse and then we

would just pull in that string for

local storage so local storage dot get

item and then remember we named it

example pet data okay at this point

let's test out the feature so if we add

a new pet test cat age of four and add

it as expected we see it here but now if

we cause the page to reload so maybe in

our code if we get rid of this comment

just to trigger code pen to reload the

example area if we check it that data is

still there

perfect so now if you saved your code

pen and you closed your browser and then

you pulled this code pen back up even a

week or two from now that data would

persist and even though persistent data

has nothing to do with react you're

starting to see how useful the use

effect cook function can be let me put

that comment back since everything in

react is based around our state it's

incredibly powerful to be able to run

custom functions whenever a certain

piece of state changes if you're still

not crystal clear on why use effect is

so great that's okay

trust me we are going to use it many

times throughout this course in fact

right now let's improve our time area

component by leveraging use effect let

me show you what I'm getting at so in

our code let's find that time area

component for me it's around line number

102 it's probably in a different spot

for you but we're just looking for time

area function and currently we're using

set timeout and we're waiting one second

before we update the state with the new

time and then that's going to cause this

function to re-render again which is

going to run this code again and that's

going to create sort of an infinite loop

of that so instead of us needing to

constantly recreate a new timeout and

recreate a new timeout it would be more

efficient if we used an interval instead

of a timeout an interval is just an

ongoing instance in the browser that's

going to fire the function once every

second now in the past before we knew

about use effect we couldn't use set

interval because remember this function

is going to rerun every time the state

changes and we wouldn't want to have an

ongoing or

finit number of intervals going however

with use effect we can run a bit of code

only the first time this component

renders let me show you what I mean so

in order to save a little bit of typing

I want you to copy this line into your

clipboard just this set the time line

here where we're pulling in the to

locale string copy that okay and then we

can get rid of this set timeout area and

instead we can use use effect remember

it takes two arguments a comma B for the

second argument or the B placeholder

let's say an empty array right that's

how you say you want something to run

only the first time it renders okay and

then instead of the a argument let's

include an arrow functions of empty

parentheses arrow symbol curly brackets

and then let's drop down okay and now

here is where we can use set interval

instead of set timeout so we could say

set interval this also gets two

arguments so a comma B the second

argument is how many milliseconds you

want to wait in between each calls at

1000 and the first argument is a

function that you want to run so we

could just include an arrow function we

don't even need curly brackets and then

you could just paste in your clipboard

okay and if we check our preview area

cool

so our timer is still working only now

the web browser isn't having to

constantly recreate a timeout and

recreate a timeout endlessly there's

just one interval that continues to run

but our code isn't going to continually

rerun that and create new intervals

because use effect is only going to call

this the very first time our component

renders now this isn't super important

in this simple of an application but in

the real world whenever you're doing

something in the future you want to be

able to cancel it or negate it if this

component gets unmounted or removed from

the page before this action completes so

for example our application was more

complex and you could navigate to a new

screen that did not need to show the

time well then this time area component

would be unmounted or would no longer be

displayed

and in that case we would want to clear

the web browsers set interval right

because then it would just be a waste of

computer resources so here's what we can

do at the start of this set interval

line we can create a constant variable

let's call it just interval equals okay

and then below this line but still

within the use effect function whatever

we return within our use effect function

is what's going to be used as its

cleanup function so let's just give it

an arrow function and then we can use

the web browsers clear interval function

and we would just clear the interval

that we just named interval big picture

within use effect you can return a

function that react is intelligent

enough to use as your clean up function

so that if this component is no longer

needed on the screen well the web

browser has a way of cleaning up your

side effects or your effects now if

you've made it this far give yourself a

pat on the back because we have

completed the ten days of react or the

first chapter in this course so where do

we go from here well there is definitely

more to react than what we've covered so

far but the building blocks that we've

covered in these ten lessons form the

foundation of what makes react so

special from here we're going to change

gears and start building an actual

real-world application with a decent bit

of complexity to it so in the next

chapter we're going to start creating a

social media app together now creating

the backend and writing the code that

directly queries the database is

completely outside the scope of a

front-end course about react but rest

assured in this app we are absolutely

going to be working with a real back-end

we just aren't creating the backend it's

pre created the idea though is that

we're going to learn everything you need

to know about react in order to build a

responsive blazingly fast user interface

that seamlessly communicates with real

data or real back-end at this point

we've eaten our metaphorical broccoli

and this is where our progress is just

gonna start skyrocketing I'm so excited

to jump into this with you so let's keep

things rolling and I will see you in the

next chat

after to get immediate and lifetime

access to the full 15 hour video course

you can find a heavily discounted coupon

link in the description for this video

thank you so much for watching and take

care

[Music]

Be the first to comment “useEffect Hook In React / Load and Save State from LocalStorage: The 10 Days of React JS (Day 10)”

Your email address will not be published.

There are no comments yet.