GLOBAL ACADEMY OF TECHNOLOGY
DEPARTMENT OF INFORMATION SCIENCE & ENGINEERING
VI SEMESTER -2024-25
FULL STACK DEVELOPMENT (Integrated)
(22ISE61)
Module 4: ReactState and Express
React State: Initial State, Async State Initialization, Updating State, Lifting State
Up, Event Handling, Stateless Components, Designing Components, State vs. Props,
Component Hierarchy, Communication, Stateless Components.
Express: REST API, GraphQL, Field Specification, Graph Based, Single Endpoint,
Strongly Typed, Introspection, Libraries, The About API GraphQL Schema File, The
List API, List API Integration, Custom Scalar types, The Create API, Create API
Integration, Query Variables, Input Validations, Displaying Errors.
Text Book 2: Chapter 4,5
React State
• State is a built-in object that stores property values that belong to a component.
When the state object changes, the component re-renders.
• To make components that respond to user input and other events, React uses a
data structure called state in the component.
• The state essentially holds the data, something that can change, This state needs
to be used in the render() method to build the view.
• It is only the change of state that can change the view. When data or the state
changes, React automatically re-renders the view to show the new changed
data.
React State
Initial State
The state of a component is captured in a variable called [Link] in the
component’s class, which should be an object consisting of one or more key-
value pairs.
where each key is a state variable name and the value is the current value
of that variable.
React does not specify what needs to go into the state, but it is useful to store
in the state anything that affects the rendered view and can change due to any
event. These are typically events generated due to user interaction
React State
Initial State
For the IssueTable component,
• the list of issues being displayed is definitely one such piece of data that both
affects the rendered view and can also change when an issue is added, edited,
or deleted.
• The array of issues is therefore an ideal state variable
React State
Initial State
that do not affects the DOM:
size of the window: Even though the display changes (for example, a line may wrap
because the window is narrower), the change is handled by the browser directly
based on the same DOM. So, we don’t need to capture this in the state of the
component.
does affect the DOM:
the height of the window determines how many issues we display, we may store
the height of the window in a state variable and restrict the number of IssueRow
components being constructed.
React State
• Setting the initial state needs to be done in the constructor of the component.
This can be done by simply assigning the variable [Link] to the set of
state variables and their values.
• Let’s use the variable initialIssues to initialize the value of the state variable
issues like this:
[Link] = { issues: initialIssues };
• we used only one state variable called issues
...
const issues = [
const initialIssues = [
{ id: 1, status: 'New', owner: 'Ravan', effort: 5, created: new Date('2018-08-15'), due: undefined,
},
...
class IssueTable extends [Link] {
constructor() {
super();
[Link] = { issues: initialIssues };
}
render() {
const issueRows = [Link](issue =>
const issueRows = [Link](issue =>
<IssueRow key={[Link]} issue={issue} />
);
React State
Async State Initialization
In React, state initialization is usually synchronous and static — meaning it’s typically set
with a value or a function that returns a value. However, sometimes you need to initialize state
asynchronously, like fetching data from an API before setting state.
The state can only be assigned a value in the constructor. After that, the state can be modified,
but only via a call to [Link]’s [Link]() method.
This method takes in one argument, which is an object containing all the changed state
variables and their values. The only state variable that we have is the one called issues, which
can be set to any list of issues in a call to [Link]() like this:
... [Link]({ issues: newIssues }); ...
React State
Async State Initialization
Since at the time of constructing the component, we don’t have the initial data, we will have to assign an
empty array to the issues state variable in the constructor.
...
constructor() {
[Link] = { issues: [] };
...
we’ll use a setTimeout() call to make it asynchronous. In the callback to the setTimeout() call (which will
eventually be an Ajax call), let’s call [Link]() with the static array of initial issues like this:
...
loadData() {
setTimeout(() => {
[Link]({ issues: initialIssues });
}, 500);
}
React State
the fact is that the constructor only constructs the component (i.e., does all the
initialization of the object in memory) and does not render the UI.
The rendering happens later, when the component needs to be shown on the screen.
If [Link]() gets called before the component is ready to be rendered, things
will go awry.
You may not see this happening in simple pages, but if the initial page is complex
and takes time to render, and if the Ajax call returns before rendering is finished,
you will get an error.
React State
Apart from the constructor and the render() methods, the following lifecycle methods of
a component could be of interest:
• componentDidMount(): This method is called as soon as the component’s
representation has been converted and inserted into the DOM. A setState() can be called
within this method.
• componentDidUpdate(): This method is invoked immediately after an update occurs,
but it is not called for the initial render. [Link]() can be called within this method.
The method is also supplied the previous props and previous state as arguments, so that
the function has a chance to check the differences between the previous props and state
and the current props and state before taking an action.
React State
• componentWillUnmount(): This method is useful for cleanup such as cancelling
timers and pending network requests.
• shouldComponentUpdate(): This method can be used to optimize and prevent a
rerender in case there is a change in the props or state that really doesn’t affect the
output or the view.
This method is rarely used because, when the state and props are designed well,
there will rarely be a case when the state or props change but an update is not
required for the view
React State
The best place to initiate the loading of data in this case is the
componentDidMount() method. At this point in time, the DOM is guaranteed
to be ready, and setState() can be called to rerender the component.
...
componentDidMount()
{
[Link]();
} ...
React State
React State
Updating State
Let’s add a new issue and thus change, not the complete state, but only a portion of
it.
To start, let’s add a method in IssueTable to add a new issue. This can take in as an
argument an issue object, to which we’ll assign a new ID and set the creation date. The
new ID can be calculated from the existing length of the array.
...
createIssue(issue) {
[Link] = [Link] + 1;
[Link] = new Date();
}
React State
Updating State
• Note that the state variable cannot be set directly, nor can it be mutated
directly.
• That is, setting this. [Link] to a new value or modifying its elements is
not allowed. The variable [Link] in the component should always be treated
as immutable.
• For example, the following should not be done:
... [Link](issue); // incorrect! ...
React State
Updating State
• The only way to let React know something has changed, and to cause a rerender, is to call
[Link]().
• Further, [Link]() may cause the changes that are done directly to the state variable to
be overwritten. So, the following should not be done either:
...
issues = [Link]; [Link](issue);
// same as [Link]()!
[Link]({ issues: issues });
...
The simple way to make a copy of an array is using the slice() method. So
let’s create a copy of the issues array like this:
... issues = [Link]();
React State
Lifting State Up
In React, "lifting state up" refers to the process of moving state from a child component
to a common parent component so that it can be shared among multiple child components.
Instead of maintaining separate state values in each component, the state is kept in the
parent component. This parent component then passes the state and any necessary functions
as props to its child components.
there is no straightforward way to communicate between siblings in React. Only parents
can pass information down to children; horizontal communication seems hard, if not
impossible.
React State
Lifting State Up
Here are some common scenarios where lifting state up is necessary:
• Synchronization: When multiple components need to stay in sync with a shared state
(e.g., form inputs).
• Communication Between Components: If sibling components need to
communicate, the state is lifted to the parent so that it can manage the flow of data
between them.
• Centralized State Management: It keeps the state centralized, making it easier to
debug, maintain, and modify as the app grow
React State
Lifting State Up
How to Lift State Up in React?
• Identify the shared state
• Move the state to the common ancestor
• Pass the state as props
• Handle state updates
[Link]
fac7f08eef6b587f
import React, { Component } from "react";
import "./[Link]"; render() {
import Counter from "./components/Counter"; return (
<div className="App">
class App extends Component { <Counter
state = { count={[Link]}
count: 0 decrement={[Link]}
}; increment={[Link]}
/>
increment = () => { <Counter
[Link]({ count={[Link]}
count: [Link] + 1 decrement={[Link]}
}); increment={[Link]}
}; />
</div>
decrement = () => { );
[Link]({ }
count: [Link] - 1 }
});
}; export default App;
Event Handling
In React, event handling is the way to respond to user interactions like clicks,
typing, form submissions, etc.
React handles events in a way that's similar to regular HTML/JavaScript, but
with a few key differences:
– Events are named using camelCase
– Event handlers are passed as functions, not strings
– React uses a SyntheticEvent wrapper for browser compatibility
Event Handling
HTML React
onclick="myFunction()" onClick={myFunction}
Uses string as handler Uses function reference
Events are lowercase Events are camelCase (onClick)
Inline functions are strings Inline functions are JS expressions
Basic Syntax in React
<button onClick={handleClick}>Click Me</button>
import React from 'react';
function ClickExample() { Explanation:
// Event handler function •handleClick: A function defined in the
component. It will run when the button is clicked.
const handleClick = () => {
alert('Button was clicked!'); •onClick={handleClick}: Attaches the
}; handleClick function to the button's click event.
return (
•alert(): Displays a popup message when the
<div> event is triggered
<h1>React Event Handling Example</h1>
<button onClick={handleClick}>Click Me</button>
</div>
);
}
export default ClickExample;
Using Parameters in Event Handlers
function ClickWithParams() {
const handleClick = (name) => {
alert(`Hello, ${name}!`);
};
return (
<button onClick={() => handleClick('Alice')}>Greet</button>
);
}
Handling Events in Class Components
import React, { Component } from 'react';
class ClassClick extends Component {
handleClick = () => {
alert('Clicked from class component!');
};
render() {
return <button onClick={[Link]}>Click Me</button>;
}
}
Handling Form Submission
function FormExample() {
const handleSubmit = (event) => {
[Link](); // Prevents page reload
alert('Form submitted!');
};
return (
<form onSubmit={handleSubmit}>
<input type="text" placeholder="Enter something" />
<button type="submit">Submit</button>
</form>
);
}
Stateless Components
A stateless component is a functional component that does not manage or hold any
internal state using useState or [Link].
It simply receives props and renders UI based on those props. It is also known as a
presentational component or dumb
component.
Feature Stateless Component Stateful Component
Functional or Class
Type Functional Component
Component
State Management ❌ No state ✅ Uses useState or [Link]
Side Effects ❌ Typically none ✅ Often has side effects
Purpose UI / Presentational Logic / State management
import React from 'react'; Explanation:
•Greeting is a stateless component.
function Greeting(props) {
return <h1>Hello, {[Link]}!</h1>; •It takes props as input.
} •It renders UI based on the name prop.
•No state or side effects are involved
export default Greeting;
Stateless components are:
• Lightweight
• Reusable
• Easy to test
• Great for rendering based on props
They are the building blocks of large-scale React applications when combined with
stateful containers and hooks.
Designing Components
Designing Components
Component Hierarchy
Split the application into components and subcomponents
Decide on the granularity just as you would for splitting functions and objects.
The component should be self-contained with minimal and logical interfaces to the
parent.
If you are passing in too many props to a component, it is an indication that either
the component needs to be split, or it need not exist: the parent itself could do the
job.
Designing Components
Communication
Communication between components depends on the direction.
Parents communicate to children via props; when state changes, the props automatically
change.
Children communicate to parents via callbacks.
Siblings and cousins can’t communicate with each other, so if there is a need, the
information has to go up the hierarchy and then back down. This is called lifting the state up.
the one-way data flow strictly: state flows as props into children, events cause state
changes, which flows back as props
Program 6: Counter
import React,{useState,useEffect} from "react";
const Counter=()=>{
const [count,setCount]=useState(0);
useEffect(()=>{
[Link]("Fetching inital count...");
setTimeout(()=>{
const initialcount=5;
setCount(initialcount);
[Link]("Intial count loaded:",initialcount);},1000);
},[]);
const increment=()=>setCount(count+1);
const decrement=()=>setCount(count-1);
const Double=()=>setCount(count*2);
const reset=()=>setCount(0);
return(
<div style={{textAlign:"center",marginTop:"50px"}}>
<h1>Counter:{count}</h1>
<button onClick={increment}>Increment</button>{" "}
<button onClick={decrement}>Decrement</button>{" "}
<button onClick={Double}>Double</button>{" "}
<button onClick={reset}>Reset</button>
</div>
);
};
useState — Managing Component State
useState is a Hook that allows you to add state to functional components.
const [state, setState] = useState(initialValue);
useEffect — Handling Side Effects
useEffect is a Hook that lets you run side effects in your components:
• Fetch data
Syntax
• Set up subscriptions useEffect(() => {
• Manually update the DOM // Side effect code here
• Set timers
return () => {
// Optional cleanup
};
}, [dependencies]);