0% found this document useful (0 votes)
54 views8 pages

REACT-HOOKS (Usestate) & ADV. TOPICS

The document provides an overview of the useState React hook. It defines hooks, lists general hook rules, and provides examples of using useState to manage component state. Key points include: useState allows function components to have state; it returns the current state value and a function to update it; updating state does not immediately mutate state but schedules a re-render; passing a function to the setState function allows updating state synchronously based on previous state. Examples demonstrate using useState with arrays, objects, and conditionally removing or clearing items from a list.

Uploaded by

Jesse Quayle
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
54 views8 pages

REACT-HOOKS (Usestate) & ADV. TOPICS

The document provides an overview of the useState React hook. It defines hooks, lists general hook rules, and provides examples of using useState to manage component state. Key points include: useState allows function components to have state; it returns the current state value and a function to update it; updating state does not immediately mutate state but schedules a re-render; passing a function to the setState function allows updating state synchronously based on previous state. Examples demonstrate using useState with arrays, objects, and conditionally removing or clearing items from a list.

Uploaded by

Jesse Quayle
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 8

REACT-SMILGA-S06-HOOKS (useState) & ADV.

TOPICS

PROJECT START UP
HOOK DEFINITION
GENERAL RULES OF HOOKS
USE STATE HOOK EXAMPLE (TO TRIGGER RE-RENDER)
THE USE STATE HOOK
INITIAL RENDER & RE-RENDER
USESTATE HOOK DEMO (DYNAMIC LIST OF PEOPLE W/ BTNS TO REMOVE A PERSON
OR ALL PPL)
Automatic Batching
USESTATE WITH OBJS
USESTATE DOES NOT IMMEDIATELY MUTATE THE STATE
PASSING A FN TO USESTATES SET FN TO MUTATE STATE IMMEDIATELY
PROJECT START UP
1. Copied his Repo Code (“03-ADV-React”) into my Smilga DIR
2. VSCODE 1. npm install 2. npm run dev
3. ALT/Clk L/Host Link in Terminal to Open PG
*At the Start of ea. Tutorial = have to Import the Starter into App.jsx

HOOK DEFINITION
*”A Hook is a special function that lets you “hook into” React features. “

GENERAL RULES OF HOOKS


*They ALL START w/ “use” (Even your Custom Hooks - MUST)
*Components they’re In must Start w U/Case (Components have to anyway)
*Hook MUST be Invoked Inside FN/Component Body (NOT Outside)
*Don’t Call Hooks Conditionally - eg. In an IF S/Ment, etc
*Set FNs Dont Update the State Immed.

USE STATE HOOK EXAMPLE (TO TRIGGER RE-RENDER)


*We set up a BTN to Incr. a Counter that Render’s on PG - BUT (even though it was Incr.) it kept
Displaying the Counters Original VAL on PG
*To get this to work in REACT - need:
1. A State VAL
2. Trigger a Re-Render

THE USE STATE HOOK


*useState is a React Hook that lets you add a state variable to your component. - eg. current
Count of an Incrementer
*The React useState Hook allows us to track state in a function component.
*The Convention for Naming the 2 VARs in useState is: [something, setSomething]
*Its Good Practice to Set Up “useState” even if you N/Th is going to Change (bc it could in the
Future)
*Import it into Component first: > import { useState } from 'react';
*The Parameter Accepted (Called its “initialState”) is its INITIAL STATE - eg
> const [count, setCount] = useState[0]

If you pass a function as initialState, it will be treated as an initializer function. It should be


pure, should take no arguments, and should return a value of any type. React will call
your initializer function when initializing the component, and store its return value as the
initial state.
*useState returns an array with exactly two values:
1. The current state. During the first render, it will match the initialState you have passed.
2. The set function that lets you update the state to a different value and trigger a
re-render.

INITIAL RENDER & RE-RENDER


*In a React application, the initial render is the first time that the component tree is rendered
to the DOM. It happens when the application first loads, or when the root component is
first rendered. This is also known as "mounting" the components.
Re-renders, on the other hand, happen when the component's state or props change, and
the component needs to be updated in the DOM to reflect these changes. React uses a
virtual DOM to optimize the process of updating the actual DOM, so that only the
necessary changes are made.

*There are a few ways that you can trigger a re-render in a React component:
1. By changing the component's state or props. When the component's state or props
change, React will re-render the component to reflect these changes.
2. When the parent element re-renders, even if the component's state or props have not
changed.

USESTATE HOOK DEMO (DYNAMIC LIST OF PEOPLE W/ BTNS TO REMOVE A PERSON


OR ALL PPL)
*KEYS:
1. Import useState & our Data
2. Create a Component
3. Inside it - Destr. “useState” (which is Passed(& Initialised to) our “data) into an ARR (“people”)
& a FN (“setPeople()”) > const [people, setPeople] = useState(data);
4. Create 2 Handlers for the 2 BTNs
- “removeItem()” (Removes an Indiv. Person)
- “clearAllItems ” (Removes ALL PPL)
5. “removeItem()” Handler uses FILTER MTHD to Create New ARR of PPL who !== person.id
- This New ARR is what will get passed to MAP for the Re-Render -
- By Calling “setPeople(newPeople);” - w/ the NEW (Filtered) ARR
6. “clearAllItems” - the Only S/MENT in this FN: > setPeople([]);
setPeople([]) - is the FN Passed to “useState” HOOK
setPeople([]); - passes an Empty ARR to MAP - thus NO PPL are Rendered on
Re-Render
// Import the useState HOOK (HOOK = a Special FN )
import { useState } from 'react';

// "data" = ARR of OBJs


import { data } from '../../../data';

// Component
const UseStateArray = () => {
// Destr. the useState [] - into its VAR & its FN
// Initialise its Inital State to that of "data" (which we Imported)
// "data" is Reference to an OBJ w/ PROPs = 1. id 2. names (of ppl)
// So: "people" VARs VAL is the OBJ
const [people, setPeople] = useState(data);

//// FNs for BTN EVTs


const removeItem = (id) => {
const newPeople = people.filter((person) => person.id !== id);
setPeople(newPeople);
};
const clearAllItems = () => {
// Pass Empty [] - so NO PPL
// ... Uses the FN Passed to "useState" Hook - to Update the VAR Passed to it
// ... this will OVERWRITE the Orig. [] (= ARR of OBJs) w/ Empty ARR
// ... & thus will Remove the List of PPL & Re-Render the PG (bc Re-Render A/M happens
when STATE is Changed)

setPeople([]);
};

return (
<div>
{/* // Pass ea. OBJ (as "person") Into MAP */}
{people.map((person) => {
// Destr. the VALs- From OBJ ("person") PROPs
const { id, name } = person;

//
return (
<div key={id}>
<h4>{name}</h4>

{/* doesnt get Invoked straight away bc its Inside an ANon FN */}
<button type="button" onClick={() => removeItem(id)}>
remove
</button>
</div>
);
})}

<button
type="button"
style={{ marginTop: '2rem' }}
className="btn"
onClick={clearAllItems}
>
clear items
</button>
</div>
);
};

export default UseStateArray;

Automatic Batching
*In React, "batching" refers to the process of grouping multiple state updates into a single
update. This can be useful in certain cases because it allows React to optimize the
rendering of your components by minimizing the number of DOM updates that it has to
perform.
*By default, React uses a technique called "auto-batching" to group state updates that
occur within the same event loop into a single update. This means that if you call the
state update function multiple times in a short period of time, React will only perform a
single re-render for all of the updates.
*React 18 ensures that state updates invoked from any location will be batched by
default. This will batch state updates, including native event handlers, asynchronous
operations, timeouts, and intervals.

This means that - these STATE UPDATES are Updated via AUTO-BATCHING
const displayPerson = () => {
//
setName('john');
setAge(28);
setHobby('screaming');
};
USESTATE WITH OBJS
*bc the VAR that useState uses will Hold either a VAL (if only 1 VAL) OR an ARR (if
more than 1 VAL) - sometimes we need it to Hold an OBJ

const UseStateObject = () => {


// Pass useState an OBJ
// "person" VAR Holds the OBJ
const [person, setPerson] = useState({
name: 'peter',
age: 24,
hobby: 'read books',
});

// Update the "person" OBJ - w/ Diff. VALs


const displayPerson = () => {
//
setPerson({
name: 'john',
age: 28,
hobby: 'screaming',
});
};

// Render PG - w/ Embedded OBJ VALs


return (
<>
<h3>{person.name}</h3>
<h3>{person.age}</h3>
<h4>Enjoys : {person.hobby}</h4>
<button className="btn" onClick={displayPerson}>
show john
</button>
</>
);
};
*1 thing to be aware of though is that you can overwrite the Whole OBJ if only trying to
Update 1 OBJ PROP
- eg. setPerson({ name: ‘susan’} - would Overwrite the OBJs PROPs (& thus
would only have 1 PROP)
*Solution is to SPREAD a COPY of the OBJ & Add the Updated PROP
> setPerson({ …person, name: ‘susan’ });

USESTATE DOES NOT IMMEDIATELY MUTATE THE STATE


*Instead, it schedules an update to the state and tells React that it needs to
re-render the component. The actual state update will be performed as part of the
next rendering cycle. Be mindful when you need to set state value based on a
different state value.
- eg. when we Set up a BTN to Increase a Counter which Renders the Count on PG -
the Count Rendered on PG is Correct BUT the C.LOG is 1 Count Behind
- eg. Count Renedered on PG = 1 / Count C.LOG = 0

PASSING A FN TO USESTATES SET FN TO MUTATE STATE IMMEDIATELY


*He showed how to get Around this by PASSING a FN into the SET FN - which:
1. Created a New VAR that was the OLD VAL + 1
2. Returned that new VAR (to the useState VAL)

const UseStateGotcha = () => {


const [value, setValue] = useState(0);

const handleClick = () => {

// PASS IN the VAL that is Currently in the STATE (In STATES “value”) as
currentState
setValue((currentState) => {

// Create a NEW VAR to Hold the Incr. VAL


const newState = currentState + 1;

// Return the “newState” VARs VAL - to the STATES “value” VAR


return newState;
});
};
*If you want to update the state immediately and synchronously, you can pass a
function to setState that receives the previous state as an argument and returns the
new state
setState enqueues changes to the component state. It tells React that this
component and its children need to re-render with the new state. This is the main
way you’ll update the user interface in response to interactions.

You might also like