2026-08-19 15:05

Status:


IBM - DFAR - In-depth Understanding of React Functionality

==Hooks and Form Management in React

  • Hooks
    • Hooks introduced in React version 16.8, hooks basically try to simplify the challenges that are proposed by writing class components, letting you write functional components with the same capabilities as class components

    • This means you can actually use state within of a functional component, sort of turning the actual functions into classes themselves but without all of the hoopla. This means you can preserve a component’s state on it’s update

    • This gives you the same functionality with far less complexity you can hook into react’s state and life cycle features with functions

    • Custom hooks you can basically write your own hooks, which can be used across multiple components, and generally prevents things like code duplication

    • Advantages of Hooks

      • More readable code
      • Less code overall when setting things up
      • Optimized code by react’s own backend
      • Simplify your code
      • Handle things like events and logic without classes
      • Give a performance boost to your code
    • You can only with hooks with function components not any of the other types. And they must be called at the top of the component three (the parent element)

    • This means you cannot call them inside of regular JS functions, inside loops, conditionals, or nested functions either, which is a bummer

    • Below Hand are specified the needed versions with which you can use React hooksPasted image 20260819164141.png

    • Common Hooks

      • useState allows you to add state to a function or component and is covered in more detail inside of DFAR - Module 3 - In-depth Understanding of React Functionality
      • useEffect manages things like side effects, including DOM changes and HTTP requests, and is mostly used with fetching data from a database
      • useContext manages context changes and provides access to a change in context
      • useReducer this manages Redux State changes, which are covered in more detail down below
    • Pasted image 20260819164559.png

    • Writing custom hooks in order to create your own hook, you use the prefix use so for example useLocalStorage or useAuth

    • These custom hooks are composed of one or more hooks total, letting you basically combine them into a multi-tool

    • They have the same features as JS functions

  • Side-Effects Management and Custom Hook
    • useEffect is a react hook that allows you to perform side effects in functional components. These are basically any operation to execute on page upload, which can be things like fetching API data, subscribing to events, or manipulating the DOM for animations
    • These side affects tend to happen asynchronously and tend to affect the application’s inner state and the outer UI
    • Below is a useEffect example and side effect, it basically uses an API in order to fetch data upon the loading of the page, which is stored inside of an internal state with the use of an array, upon which that state is rendered out in the JSX code
    • Pasted image 20260819164835.png
    • Pasted image 20260819164937.png
    • Dependencies in useEffect are basically variables or values used to determine whenever useEffect should actually run
    • These are specified as an array argument to the useEffect function see more examples down in the image below
    • Pasted image 20260819165134.pngPasted image 20260819165204.png
    • These events would run again whenever the actual inner passed in variable or state changes, so in the image above, whenever the count basically gets updated, then the effect will get re-ran
    • If the array is omitted entirely, than the effect will run AFTER EVERY SINGLE RE-RENDER
    • Custom hooks let you create re-usable logic, they allow you to abstract complex logic that you can very easily reuse across a large number of your components in a given applications
    • Below is an example of a custom hook, in which you have a toggle state and then a toggle button, whenever the boolean tags, the ON or OFF portion of the button is logically switches
    • you can then use the custom hook useToggle to sort of combine this behavior into one thing instead of having it be separated outward, making it more concise and letting you save up on some code
    • Pasted image 20260819165615.png
  • Connecting React to External Services
    • External Services are basically third party platforms, programs, or infrastructure that your application connects to over a network
    • These are hosted on some other endpoint in a network that you would connect to, and provide a ton of different things like features, tools, or data
    • Letting you interact with different services and applications via APIs or Application Programming Interfaces
    • API enable your application to exchange data with outside services, they’re basically goated, and let you handle data from an outside source with a somewhat secure connection model, but need to be well guarded because they are basically kind of keys towards your data
    • Common API methods such as fetch API, and axios Library
    • Pasted image 20260819165941.png
    • In the code, an outside variable stores the API url from a fake source for educational purposes
    • Then, the fetch method basically sends out a network request over to the thing located inside of that API link, and this starts the get process of the info
    • You connect the .then method over to the fetch call, which takes a callback function as an argument and runs it whenever the fetch action is sucessful, basically, what do you want to do after you actually get a response from the API
    • Depending on what you are fetching, you can convert the data via JSON or whatever other item is being used that you are accessing, letting you do things like log the data, or use the catch method in order to see if your fetch call failed
    • Axios a popular JavaScript library used for making HTTP requests from web browsers, an example is shown below
    • Pasted image 20260819170349.png
    • You need to actually install axios, and then import the needed coded from the library. You then use the get method call which works similar enough to the fetch call, at which point you also have the same logic for your .then and .catch method calls that are done in tandem
    • The real main different between this and the other one is that axios handles processing the JSON data for you sort of, so you have a bit less freedom with what you do, but a lot more convince for getting it done so no response.json() call
  • Implementing Forms
    • Forms these basically allow users to interact with data in an application, think of the wrapper for the login page for the obsidian portal, it used a form in order to get the inputted data that was in the labels
    • You would use them for user registration, surveys, and an order form
    • Areas where users interact with the website are called fields and there are many kinds of fields, text boxes, drop-down menus, radio buttons, and more
    • YOU ALSO NEED TO HANDLE THE SUBMISSION LOGIC AND DATA VALIDATION
    • This is literally what I did yesterday where you need to make sure that the data fields are not empty and are correctly filled out, and then you can send that data over to the back-end of your services for processing before then sending it back
    • HTML gives you some form elements on it’s own like <input>, <textarea>, and <select> but React gives you component state which can store in the input and make updates using the setState method, letting you check the data in real time and without DOM traversal for retrieval like you would with regular JS
    • You code must also then have submission logic that tells the application when to accept the input, so you gotta make sure that you have something like a button to submit, so you can have more assurance a person meant to submit what they did
    • You can also have validation which is retyping your password and having specific password rules, even sometimes something like an email code to ensure you are who you are, but that is more about the three A of cybersecurity and authentication than react
    • Pasted image 20260819174708.png
    • Pasted image 20260819174738.png
    • Controlled vs Uncontrolled components. Uncontrolled components, you use React to place the value on the page, and then browser is the thing that keeps track of the rest. Controlled components are the ones where state keeps track of the data, meaning you must explicit write the code to keep the state going, and track the changes
    • So while uncontrolled behaviors are easier to develop and require less coding, they are more robust, which is basically then the opposite from the controlled components
    • Basically just your own custom shit versus the stuff that is given to you by HTML
  • Lesson 1 Summary: Hooks and Forms
    • The useEffect hook in React enables the execution of side effects within functional components. In React’s useEffect hook, dependencies refer to variables or values that determine when useEffect should run.
    • Custom hooks allow you to abstract complex logic and easily reuse it across different components in your application.
    • External services are any program, platform, or infrastructure your application uses to connect to and work with other applications over a network.
    • APIs enable you to acquire data, execute operations, or add extra features to your application.
    • Within React, components typically manage form data.
    • React inputs are classified into two categories: controlled and uncontrolled. In uncontrolled input, React puts the value on the page, and the browser keeps track of the rest. Controlled inputs, require you to write the code to manage the value explicitly.

==Application State Management with Redux

  • Introduction to Redux
    • Differences between Component & Application States-, an application state holds information about the ENTIRE APPLICATION and can be generally accessed from anywhere inside of the entire application

    • So imagine something like a cart feature on a shopping site it should be accessible anywhere, letting you change it whenever you would like

    • The Redux library lets you handle the application state instead of every single component manging it on their own

    • This lets you pass on information onto components from the application state as well

    • In general, the larger an application, the more useful Redux might become, basically the more components you have, the more you might want to toss them all into a single application state instead

    • You will also have components sharing the same data but in different locations so you can generally pass data much easier with Redux, without passing it weirdly through the DOM tree

    • NOTE: you can use Redux independent of just React, you can use things like Angular, Vue, or even plain old JS with Redux, even if it is mostly popular with React

    • Redux Store is basically a data structure that is used to store and manage data, sort of a single source of truth, and is where the actual application state data gets stored in the end

    • Benefits of Redux include a better readability and less complex code, making it easier to predict the state of the application, and makes it easier to maintain the code for the above hand reasons as well

  • Essential Concepts of Redux
    • Redux offers a centralized state management system for your application. Whenever using Redux, you do not need to manage component states, as they are managed at the application level, meaning component properties are immutable
    • So you can generally create new state objects instead of altering current ones
    • Redux Elements- it uses actions, stores, and reducers when updating component properties
      • Store - contains all current states in the application
      • Action- object that indicates state change intent, but now how to actually change it or anything like that
      • Reducer- specifies HOW to actually change the state
    • Actions basically an action creator function like addItem() or something like that, which is an action creator, because it creates and returns an action object. This component action object is then sent over to the store using another dispatch function
    • The entire above hand process is called Dispatching and Action
    • Store this is the data structure that basically holds ALL of the application states, including the state of the cart in this example, like the number of items.
    • The store uses a data structure called a state tree, and it has it’s own methods to manage different properties
    • Action Object Properties this basically describes the action that needs to be taken, it would contain things like a type & payload, and the store uses that type property to indicate to the reducer what should be changed in that given state
    • Reducer the store basically calls this whenever it needs to change or update some portion of the application state, passing in both the action object and state object into the reducer function in order to calculate the new state
    • A reducer function has no side effects or mutating functions
    • Why this architecture?
      • this architecture enables a predictable state container by making sure there are explicit state changes, meaning you can read the code A-LOT easier by separating the action description from how to update
  • Async with Redux
    • Operation Behavior
      • Synchronous - basically means that, when given two operations, one operation must complete execution before the next one can begin
      • Asynchronous This one is basically the inverse, where two or more operations are able to work and complete in tandem to one another
    • When to use async you generally would want to use this whenever you want to run an application without blocking the actual use of the application, so something like say you need to fetch some data or something, or some really memory intensive calculation that you need to get done, especially useful in things like games if you want to think of it like that
    • Problems with async generally the issue from this comes along if you have something that relies on another process for information, basically you cannot do something like process the payment and validate the card information asynchronously, you need to make sure that each one of those happens in order, for logical ability basically
    • Pasted image 20260819213427.png
    • JavaScript generally tends to behave asynchronously but redux on the other hand tends to require sync behavior, which I would assume would make it slower
    • It does make sense though because you first need to create the action object, send it over to the store, where it only then finally is processed with the reducer based on the type of the object
    • Middle-ware allows you to interact with asynchronous data. To perform state changes, you do so with actions from the store, but if necessary, the middle-ware might intercept these actions and delay them to support given async behavior, where then things go back to normal, and eventually the sync behavior is restored
    • Popular middle-wares include: Thunk & Saga
    • Thunk- returns functions instead of action objects like regular redux might, letting you interact with the store using these functions, and letting you perform async operations like API calls and what not
    • It is good for simple applications, and is easy to learn, but it does have concurrency issues and does not scale well
    • Redux Saga introduces things called “generator functions” also called “Sagas” which allow you to Encapsulate async logic and let you handle those kinds of async operations as mentioned above
    • They allow for multitasking with dispatch processes, by pausing and resuming actions as needed
    • Saga is very easy to test and debug, and scales tell, it has a tight learning curve, but a pretty big pay off
  • Binding Redux and Flow
    • State Change in React in a given react application, state change generally causes the re-rendering of the DOM
    • However, as the application expands, it becomes rather difficult to actually manage the entire handling of data inside of your application
    • As it might involve a long chain of transfer of data between props and what not, and as previously said, this is generally solved by the use of Redux
    • Generally, the Redux library would come with a single store and a single reducer off of rip, but it does expand out on the number or reducers as the application you are making grows
    • Below-hand is basically just an info-graphic that displays the different building blocks mentioned in the previous video, basically the main parts of how redux works
    • Pasted image 20260819214324.png
    • Pasted image 20260819214551.png
    • The data glow inside of Redux is also unidirectional and beings whenever a user interacts with the UI, and then the action is dispatched and created with the action creator, the Root Reducer then gets it’s hands on it, letting it be passed on to the other reducers, based on the given type of the action object
    • This is then checked by using a simple switch statement to filter out the required actions, and if the type of the required action matches, it returns a newly updated state
    • The state DOES NOT CHANGE IN REDUX, and instead CREATES A NEW ONE WITH THE GIVEN CHANGES
    • The store then updates the UI with the newly updated component as well
  • Introduction to Redux Toolkit
    • Redux Toolkit is an official package that the Redux team provides in order to simplify out development and make it more efficient

    • It includes a bunch of utils that help to reduce needed boilerplate for you to write, and also streamline common redux tasks

    • Redux toolkit utilities

      • Simplified store setup a configureStore() function which basically reduces the whole need for you to manually set up the redux store into just a single given function, it also includes setting up the store with common middle-ware like Thunk or DevTools Exension
      • Immutability and reducer logic a createSlice() function which allows for developers to create slice reducers which automatically handle updates to the state in your application, making it easy to write reducer functions
      • Boilerplate reduction basically as it sounds, let you write pretty neat and concise code without needing to set up a bunch of different boilerplate before you can get to what you want to actually write
    • You can install the Redux Took Kit RTK with the following command npm install @reduxjx/toolkit

    • Pasted image 20260819215356.png

    • The redux toolkit generally includes one Slice file and then one store file, with the given characteristics and portions of them being defined above in the info-graphic

    • Slices define parts of the application state and logic to update them

    • Store is where all of these different slices combine together to form an application state tree

    • Each slice reducer is integrated into the store during it’s creation using the configureStore() function, these are then combined into a single given reducer using the combineReducers() function. Lastly, when the actions are dispatched, the store delegates them to the appropriate slice reducer

    • Below hand is a visual example of the relationship between slices and stores using an e-commerce applicationPasted image 20260819215659.png

  • Lesson 2 Summary: Application State Management with Redux
    • The Redux elements involved in updating the component properties include actions, the Store, and reducers.
    • Redux makes use of the entire application’s states as opposed to using component states.
    • Within Redux, the existing application states reside within an object known as the store.
    • You use action objects to communicate to the store what data you need to update and use reducers to tell the application how to make the update.
    • Reducers are pure functions that receive the current state and an action object and return a new state with the actions performed.
    • Synchronous operations run in a first-to-last sequence, beginning the next operation only after the previous one has finished.
    • Asynchronous operations can occur in parallel. They don’t require the previous operation to be completed before beginning the next.

==Cheat Sheet

Hooks and form managementDescriptionCode example
useState()useState() hook can manage states of the React function component where you can declare any data type, for example, boolean, object, array, string.1. import React, { useState, useEffect } from ‘react’;

2. function SideEffect() {

3. const [empId, setEmpId] = useState(100);

4. return (

5.


6.

{empId}



7.


8. );

9. }

10. export default SideEffect;
useEffect()useEffect is a React hook that allows you to perform side effects in functional components. A side effect refers to any operation that you need to execute as soon as the page loads without calling those operations/functionalities separately, such as fetching data from an API.1. import React, { useState, useEffect } from ‘react’;

2. function SideEffect() {

3. const [foods, setFoods] = useState([]);

4. useEffect(() => {

5. fetch(‘https://api.npoint.io/d542b9ad99f501ab3dbf’)

6. .then(response => response.json())

7. .then(data => {

8. console.log(data);

9. setFoods(data);

10. })

11. .catch(error => console.error(‘Error fetching users:’, error));

12. },[]); // Empty dependency array means this effect runs only once when the component mounts

13. return (

14.


15.

Food List



16.


    17. {foods.map((food)=>{

    18. return (<>

    19.
  • {food.name}



  • 20.

    food.description



    21.

    food.price



    22.

    food.category



    23.

    food.ingredients



    24. {food.image_url}

    25. </>

    26. )

    27. })}

    28.


29.


30. );

31. }

32. export default SideEffect;
Custom hookYou can use custom hooks in any other component. In this code snippet, there is one function component known as UseToggle, which serves as a custom hook, and another function component ToggleButton, which will use this custom hook.1. //ToggleButton

2. import { useState } from ‘react’;

3. import UseToggle from ’./UseToggle’;

4. function ToggleButton() {

5. const [isToggled, toggle] = UseToggle(false);

6. return (

7.


8.

Toggle Button



9.

12.


13. );

14. }

15. export default ToggleButton;

16. //UseToggle.jsx

17. import { useState } from “react”;

18. function UseToggle(initialValue = false) {

19. const [value, setValue] = useState(initialValue);

20. const toggle = () => {

21. setValue(!value);

22. };

23. return [value, toggle];

24. }

25. export default UseToggle
fetch api methodFetch method can fetch data using API.1. const apiUrl = ‘https://jsonplaceholder.typicode.com/posts’;

2. fetch(apiUrl)

3. .then(response => response.json())

4. .then(data => {

5. console.log(data);

6. })

7. .catch(error => {

8. console.error(‘There was a problem with the fetch operation:’, error);

9. });
axios api methodAxios method can fetch data using API.1. import axios from ‘axios’;

2. const apiUrl = ‘https://jsonplaceholder.typicode.com/posts’;

3. axios.get(apiUrl)

4. .then(response => {

5. console.log(response.data);

6. })

7. .catch(error => {

8. console.error(‘There was a problem with the fetch operation:’, error);

9. });
onChangeThe onChange event attribute is often used in HTML and React to track when the value of an input field changes, like a text input. The onChange event occurs when a user writes something into an input field. This attribute lets you record and handle the changes.1. import React, { useState } from ‘react’;

2. function FormData() {

3. const [empName, setEmpName] = useState(”);

4. const handleChange = event => {

5. setEmpName(event.target.value);

6. };

7. const handleSubmit = event => {

8. event.preventDefault();

9. console.log(‘Form submitted:’, empName);

10. };

11. return (

12.


13.

My Form



14.


15.

19.

20.


21.


22. );

23. }

24. export default FormData;
Redux toolkitRedux toolkit can be installed using npm1. npm install @reduxjs/toolkit.

==Glossary

TermDefinition
Action creatorAn action creator is a function that returns an action object containing a type property (identifying the action) and optionally a payload property (data associated with the action).
Actions in ReduxActions are payloads of information that send data from the application to the Redux store, describing “what happened” in the application.
Application stateA state that holds information about the entire application.
Asynchronous or async codeA code that runs in parallel. This means an operation can occur while another is still being processed.
AxiosA popular JavaScript library for HTTP requests from web browsers.
combineReducers ()combineReducers() is a Redux function used to combine multiple reducers into a single root reducer for the Redux store.
createSlice ()A function in RTK that allows developers to define ‘slice reducers’ that automatically handle immutable updates to the state.
configureStore ()A function in RTK that combines several pieces of Redux setup logic into a single function call.
Controlled componentA component where the React state manages the form data. You must explicitly write the code to create the state and tell it how to update when the data changes.
Custom hookA new composition of one or multiple hooks.
fetchA modern JavaScript API for making asynchronous HTTP requests in the browser environment. It allows you to fetch resources, such as JSON data, from servers over the network. It is commonly used for data fetching in React applications to interact with backend servers or APIs.
FieldsAreas in a form in which users interact with the data.
FormsAllow users to interact with data on a web page.
getState ()A function in the store that allows access to the state.
HookA function that enables you to reuse code logic across components without changing component hierarchy or introducing unnecessary nesting.
Payload propertyAn optional property contains some data required to perform a task.
Reducers in ReduxActions that return the new state.
ReduxA library that can maintain the application state and pass information about the application to a component whenever it gets called.
Redux storeA data structure that stores and manages data.
Redux SagaA middleware that exposes a set of helper functions, or sagas, to create declarative effects that are plain JavaScript objects, and your sagas can yield them.
Redux ThunkRedux Thunk is a middleware for Redux that allows action creators to return functions instead of plain objects, enabling asynchronous logic (e.g., AJAX requests) within Redux actions.
Redux Toolkit (RTK)An official package the Redux team provides to simplify Redux development and make it more efficient.
Side effectsRefers to any operation you must execute as soon as the page loads without calling those operations/functionalities separately, such as fetching data from an API, subscribing to events, manipulating the DOM, or setting timers.
SliceSlice in Redux Toolkit (RTK) represents a portion of the Redux state and includes the logic for updating that slice’s state using reducers and action creators.
Store in RTKAll the slices are combined to form the complete state tree of your application.
SubscriptionSubscriptions is a mechanism in Redux that allows components to subscribe to state changes in the Redux store, ensuring they receive updates and can react accordingly.
Synchronous or sync codeA code that runs in an orderly sequence from top to bottom. This means that each operation must wait for the previous one to complete before executing.
Type propertyA string that identifies the action.
Uncontrolled componentA component where you use React to place the value on the page, and the browser keeps track of the rest.
useContext hookA hook that manages context changes and provides access to a context.
useEffect hookA hook that manages side effects such as document changes and HTTP requests.
useReducer hookuseReducer is a React hook that facilitates complex state logic in functional components, commonly used for managing Redux state updates.
useState hookA hook that allows you to add state management functionalities to function components.

References