What steps can I take to refactor a portion of the component using React hooks?

I am trying to rewrite the life cycle methods in hooks but I am facing some issues. It seems like the component is not behaving as expected. How can I correct this? Can you provide guidance on how to properly rewrite it?

useEffect(() => {
    updateUser();
});

useEffect(() => {
    if (userId !== prevUserId) {
        updateUser();
        console.log('update');
    }
}, [userId, prevUserId]);

const updateUser = () => {
    if (!userId) {
        return;
    }
    onUserLoading();
    API.getUser(userId)
            .then(onUserLoaded)
            .catch(onError);
}

Answer №1

i have implemented the use of new React hooks,

componentDidMount is now equivalent to useEffect(()=>{},[]) componentDidUpdate is now equivalent to

useEffect((prev)=>{},[YOUR UPDATE DATA VARIABLE])

the updated function will now look like this:

updateUser = () => {
  if (!userId) {
      return;
  }
  this.onUserLoading();
  this.API
          .getUser(userId)
          .then(this.onUserLoaded)
          .catch(this.onError)
}

this function will be converted into a functional component as follows:

const [userId,setUserId] = useState(props.userId); // way 1
//const userId = {props}; // way 2

useEffect((prevProps)=>{
  updateUser();
  if(userId !== prevProps.userId){
    updateUser();
    console.log('update')
  }

},[userId, updateUser])  

Answer №2

It's important to keep in mind that the impact of this method relies on updateUser and the callback passed to useEffect doesn't receive any arguments. Take a look at this example:

const User = React.memo(function User({ userId }) {
  const [userResult, setUserResult] = React.useState("");
  //this function is only created once during mounting
  const onUserLoaded = React.useCallback(
    (result) => setUserResult(result),
    []
  );
  //this function is not recreated unless userId changes
  const onUserLoading = React.useCallback(() => {
    setUserResult(`user loading for ${userId}`);
    setTimeout(
      () => onUserLoaded(`result for user:${userId}`),
      1000
    );
  }, [userId, onUserLoaded]);
  //this function is not recreated unless userId or onUserLoading changes,
  //and onUserLoading only changes when userId changes
  const updateUser = React.useCallback(() => {
    if (!userId) {
      return;
    }
    onUserLoading();
  }, [onUserLoading, userId]);
  //the effect runs when updateUser changes, which only happens when userId changes
  React.useEffect(() => updateUser(), [updateUser]);
  return <div>user result:{userResult}</div>;
});
const App = () => {
  const [userId, setUserId] = React.useState(1);
  return (
    <div>
      <button onClick={() => setUserId(userId + 1)}>
        Change User ID
      </button>
      <User userId={userId} />
    </div>
  );
};

ReactDOM.render(<App />, document.getElementById("root"));
<script src="https://cdnjs.cloudflare.com/ajax/libs/react/16.8.4/umd/react.production.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/react-dom/16.8.4/umd/react-dom.production.min.js"></script>

<div id="root"></div>

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

Running system commands using javascript/jquery

I have been running NodeJS files in the terminal using node filename.js, but now I am wondering if it is possible to execute this command directly from a JavaScript/jQuery script within an HTML page. If so, how can I achieve this? ...

Is it necessary to save every async call response in the redux store?

How should async calls be handled in react-redux? I understand that each component can make API calls independently and store data locally, but what is the purpose of the redux store then? Is it only for storing shared data between components? What are t ...

get selection choice from the server

I have been trying to update my option select menu when the button is clicked without clearing out the menu. Currently, I am using $(#id).click(function(){}); but it seems that this approach is causing the select menu to clear out. Upon further investigati ...

Experiencing a repetitive occurrence of the error: "SyntaxError: Encountered an invalid or unfore

I've encountered a persistent error when attempting to execute my index.mjs file. Here is the content of my index.mjs file: import WebSocket, { WebSocketServer } from "ws"; import http from "http"; import express from 'express ...

Encountering an issue with the removal of slides when updating JSON data for angular-flexslider

Issue: Although my JSON object is updating, the slider does not update for all resorts as expected. Sometimes it fails to update when the JSON object changes. The resorts (image collections) that do not update are throwing an error stating "cannot read pr ...

Tips for selecting the correct date on a DatePicker using selenium?

I am facing an issue with my selenium test related to a date picker on a webpage. The task is to select a specific date (e.g., 14/2/2012) by clicking on the correct day. However, the date picker is generated using jQuery as shown in the code snippet belo ...

Creating a Drop-Down Button Using HTML, CSS, and JavaScript

I am currently working with the following code: <link rel="preconnect" href="https://fonts.googleapis.com"> <link rel="preconnect" href="https://fonts.gstatic.com" crossorigin> <link href="https://fonts.googleapis.com/css2?family=PT+Sans ...

Choose a procedure to reset to the original setting

I'm attempting to achieve something that seems straightforward, but I'm having trouble finding a solution. I have a <select> tag with 5 <option> elements. All I want to do is, when I click a button (which has a function inside of it), ...

The node module.exports in promise function may result in an undefined return value

When attempting to log the Promise in routes.js, it returns as undefined. However, if logged in queries.js, it works fine. What changes should be made to the promise in order to properly return a response to routes.js? In queries.js: const rsClient = req ...

In Node.js, JavaScript, when using SQLite, the variables are inserted as Null

I have spent a lot of time searching and trying various methods, but I am still unable to solve this issue. My goal is to insert 8 variables received from an API call into an SQLite table. Although the execution seems correct, when I query the table, all v ...

Navigating a Frame and Clicking a Link with Puppeteer: A Step-by-Step Guide

I am facing an issue with clicking on an anchor link within a page that is supposed to open a new tab for exporting a PDF. The problem arises because this link is located inside a frame within a frameset structure as shown below: https://i.stack.imgur.com ...

Popup Triggered by a JavaScript Timer

Seeking assistance in creating a straightforward timer-based popup. Once the timer hits 10 seconds, the popup should become visible. The timer should pause or stop, and after clicking the 'ok' button on the popup, the timer should reset to 0. Can ...

Why was the 'Symbol' type introduced in ECMA-262-v6 and what purpose does it serve?

Can you explain the purpose of the 'Symbol' type in ECMA-262-v6? Is it used for fast path implementation for object keys? How does it work internally - does it hash with the assurance that the underlying data remains unchanged? ...

Tips on creating a horizontal scrolling effect using the mouse

Is there a way to enable horizontal scrolling by holding down the mouse click, instead of relying on the horizontal scroll bar? And if possible, can the scroll bar be hidden? In essence, I am looking to replicate the functionality of the horizontal scroll ...

Is it better to dynamically generate HTML elements or to just directly paste complete fragments in the code?

After manipulating the DOM and injecting AJAX content, I often find myself filling in the new content into a copied HTML fragment, then populating it with the updated information before using $().html() to insert the modified code back into the DOM. The ex ...

The functionality of the React Material-UI menu anchor is disrupted when interacting with a react-window

In the project I am working on, I have encountered an issue with the Material-UI and react-window integration. Specifically, the material-ui menu component does not anchor properly when placed within a virtualized list created with react-window. Instead of ...

Running Protractor tests can be frustratingly sluggish and frequently result in timeouts

After spending most of the afternoon struggling with this test, I've tried different approaches but none seem to work. The task at hand is searching for users within the company, generating a table, and selecting the user that matches the name. Curren ...

Tips for efficiently deconstructing JSON arrays, objects, and nested arrays

I'm attempting to destructure a JSON file with the following structure: [ { "Bags": [ { "id": 1, "name": "Michael Kors Bag", "price": 235, "imgURL" ...

what is the best way to eliminate comments from nested arrays when using useReducer?

Can someone help me figure out how to use useReducer and useContext to manipulate global state? I specifically need to know how to delete comments using useReducer. Data Structures View the interface image here Sample Data Array export const listsData:IDa ...

The bidirectional data binding feature is malfunctioning following an XMLHttpRequest request

When watching a property from Vuex, I use the following approach: computed: { ticket() { return this.$store.getters['order/reservation'].offer_id } }, watch: { ticket(newTicketId) { console.log('Caught change of ...