REACT 3, Fetch() API, OpenAI API translation, useState() objects and conditional rendering, useContext() Providers and useCallback()

The fetch() API provides us a javascript interface to access the protocol, by using the global method fetch() and an URL path it returns a promise that will resolve into a response object.

The protocol is the set of rules used to define data formats, needed to allow data exchange between devices.

The promise-based fetch method can implement HTTP concepts like CORS (Cross-Origin Resource Sharing), an HTTP mechanic that allows a server to set the origin (domain, port, or scheme) from which the browser permits to load resources.

//We can add an init argument to the fetch(url, init) method
let init= {
  method: 'POST',                 //GET, POST, PUT, DELETE, etc
  body: JSON.stringify({
    q: "Detectando el lenguaje"   //body data type must match "Content-Type" header
  }),
  headers: {
    'Content-type': 'application/json; charset=UTF-8',
  },
}

We use try/catch to handle network and Cors errors, but we also need to check the promise.ok property to avoid other types of errors (like 404).

Request and Response bodies can only be used once, we use a request constructor to copy a fetch() request, and the copy must be done before the body is read

To configure the OpenAi translate API in ReactJs

We can prompt single or multiple language translations.

For a single-language translation, we modify the prompt.

We use regex to create a useState() array of Node elements to render in the DOM.

chevron-rightTo render a multi-line string variable as an useState() arrayhashtag

We use regex to create an array of a multi-line string variable.

Then we use map() to create an useState() array with Node elements.

Then we can render it.

We loop through the useState() node elements and, using regex, we modify useState() to render the translation using map().

We update the useState() to get the translation to render

Render useState() arrays and objects

The useState() is a react Hook we use to have state variables in function components

To modify useState() arrays we use the spread syntax and slice() method.

The spread operator works for useState() objects too.

chevron-rightAdd, Remove and modify useState() objects guidehashtag

To render useState() objects in the DOM we use the static method JSON.stringify()

We use the spread syntax to add key/value objects to the object useState()

To delete a property from the useState() we copy it and use the delete operator, then we set it as the new useState().

To add and modify existing properties we.

useState(9 object, add, delete and editing existing properties
chevron-rightModify useState() on nested objectshashtag

We need to use the spread syntax multiple times to access nested object properties.

The same goes for first-level object properties.

We can combine them.

editing different nested properties in the object
chevron-rightModify useState() object property using a variablhashtag

We use the [variable] to substitute an object property with its splice() copy.

Conditional rendering using components props

The if statement is not a {javascript expression}, so we use the component's props in the function component to return and render JSX.

conditional rendered componentc

UseContext() and Provider components

To share data between separate and nested components we don't use props (prop-drilling), we useContext().

We set the Context provided values once.

In the imported component we deconstruct the context value object property.

And its nested components will have access to the same context value (even if imported).

The createMethod API sets a global state context object that components can Provide and read. The useContext() React hook reads the component.provided context.

chevron-rightNested component.Provider and useState value prophashtag

We can have multiple component.Provide and each child will inherit each parent context values.

The value prop can be a useState(), an object, or a function, when changed it triggers a re-render of the children's components

Context provided value child component

We import createContext() to create multiple different Context providers.

We can override specific context values for specific children.

Each time an exported Context.Provider component is used it will retain the value of its useContext() and can modify it.

chevron-rightNested component providers value increasehashtag

The parent component provides all its children with the useContext() value.

We render the useContext() value on another component.

The first level render is <h1>.

Any nested component that uses <Section> provider will render its increased value.

UseCallback() React hook with useMemo()

The context value object/props can pass functions(), and if any nested component changes then the passed function will be re-rendered, even if it returns the same value.

To optimize updating the component we useCallback() and useMemo().

The useCallback() React Hook caches/saves a function and won't trigger it unless one of its dependencies array elements changes.

Any function (){} or ()=>{} will be considered a new function, even if it includes the same values, and gets re-rendered, to avoid that we useMemo().

The useMemo() caches a function returned value while useCallback() keeps that function from re-rendering.

chevron-rightOptimizing nested component with useMemo() and useCallback()hashtag

The background-color, the onSubmit() event, and the counter useState() are part of the same component but the latter updates much slower.

In the child component, we cache a useCallback() function and pass it as a prop to the <ShippingForm/>

The theme prop is not a dependency so it won't re-render the child component.

A more generic function would have re-rendered the child component.

We useMemo() the function component, it renders the function once and caches it, while useCallback() keeps it un-rendered, ignoring other components' props changing.

Checkbox and form ae fast while counter is slow

Rendering a component is different from triggering a function within it.

The onSubmit() will trigger the useCallback() function, and if the dependencies it uses don't change, the child component doesn't get re-rendered. The useState() counter gets rendered, so it re-renders the entire components on change.

We can update an useState() in a useCallback() function without including it in the dependencies.

We useCallback() to optimize custom react hooks use.

You can't call useCallback() in a loop, extract a component for the items, and useCallback() there

chevron-rightuseCallback() component in a .map() loophashtag

We pass the map() loop item as a prop, and we return the useCallback() function using the component.

Last updated