Home > front end >  How react hooks are updating state
How react hooks are updating state

Time:05-27

I have a long process that updates the state. I want to show red background when it's running and blue when it's done.

const MapBuilder = (props) => {
    const [backgroundColor, setBackgroundColor] = useState(false);
    const [fancyResult, setFancyResult] = useState(null);

    console.log(`stop 1 backgroundColor ${backgroundColor} fancyResult ${fancyResult}`)
    const veryHardWork = () => {
         setBackgroundColor("red");
         console.log(`stop 2 backgroundColor ${backgroundColor} fancyResult ${fancyResult}`)
         for (let i = 0; i < 1000; i  ) {
            for (let j = 0; j < 1000; j  ) {
              console.log("So hard")
         }
    }

   setFancyResult("done")
   console.log(`stop 3 backgroundColor ${backgroundColor} fancyResult ${fancyResult}`)
   setBackgroundColor("blue") 
   console.log(`stop 4 backgroundColor ${backgroundColor} fancyResult ${fancyResult}`)
}

return (<div style={{background: backgroundColor}}>
   <button className="btn btn-primary" onClick={veryHardWork}></button>
</div>)
}

Here is an output of such run

stop 1 backgroundColor false fancyResult null
MapBuilder.js:13 stop 2 backgroundColor false fancyResult null
10000MapBuilder.js:16 So hard
MapBuilder.js:20 stop 3 backgroundColor false fancyResult null
MapBuilder.js:22 stop 4 backgroundColor false fancyResult null
MapBuilder.js:10 stop 1 backgroundColor blue fancyResult done

I understand from this that the state change only happens after the method veryHardWork is finished. In my real project, I actually want to show a spinner the question is how can I do it if the state is only changed at the end of the method.

I think some clarification needs to be added. In reality, I allow the user to choose a file after the user chooses the file it is loaded and some heavy processing is performed on files data while the processing is running I want to show a spinner no Asyn work involved.

Some of the answers sugested to use useEffect and moving it to a promise I tryied both but it did not help here is a different take on it which also did not work

const MapBuilder = (props) => {
  const [backgroundColor, setBackgroundColor] = useState(false);
  const [fancyResult, setFancyResult] = useState(null);
  const [startProcessing, setStartProcessing] = useState(null);

  useEffect(() => {
    let myFunc = async () => {
      if (startProcessing) {
        setBackgroundColor("red");
        await hardWork();
        setBackgroundColor("blue");
        setStartProcessing(false);
      }
    }

    myFunc();
  }, [startProcessing])

  const hardWork =  () => {
    return new Promise((resolve)=> {
      for (let i = 0; i < 500; i  ) {
        for (let j = 0; j < 100; j  ) {
          console.log("So hard")
        }
      }
      setFancyResult("sdsadsad")
      resolve("dfsdfds")
    })
  }

  return (<div style={{background: backgroundColor}}>
    <button className="btn btn-primary" onClick={() => setStartProcessing(true)}></button>
  </div>)
}


export default MapBuilder;

CodePudding user response:

The problem with the approach is that the heavy calculation is happening at the main loop with the same priority. The red color change will not ever cause any changes until all things at the event handler have been finished.

With Reach 18 you can make your heavy calculation to be with lower priority and let the UI changes happen with normal priority. You can make this happen with minor change on your code base:

const veryHardWork = () => {
  setBackgroundColor("red");

  // Set heavy calculation to happen with lower priority here...
  startTransition(() => {
    console.log(`stop 2 backgroundColor ${backgroundColor} fancyResult ${fancyResult}`)
    for (let i = 0; i < 1000; i  ) {
      for (let j = 0; j < 1000; j  ) {
        console.log("So hard")
      }
    }
    setFancyResult("done")
    setBackgroundColor("blue") 
  }
}

CodePudding user response:

So I've made you a more real world example as the code you posted doesn't look like what you're actually wanting to achieve.

The scenario to my understanding is you want to preform some setup actions to get your state / data ready before showing it to the user.

cool, so first we will need some state to keep track of when we're ready to show content to the user lets call it isLoading. This will be a boolean that we can use to conditionally return either a loading spinner, or our content.

next we need some state to keep hold of our data, lets call this one content.

each state will be created from React.useState which can be imported with import { useState } from 'react';. We will then create variables in the following format:

const [state, setState] = useState(null);

nice, so now lets do somthing when the component mounts, for this we will use React.useEffect this hook can be used to tap into the lifecycle of a component.

inside our useEffect block we will preform our set up. In this case I'll say it's an async function that get some data from an API and then sets it to state.

lastly we will use our isLoading state to decide when we're ready to show the user something more interesting than a spinner.

All together we get something like this:

import { useState, useEffect } from 'react';

const MyComponent = () => {
  // create some state to manage when what is shown
  const [isLoading, setIsLoading] = useState(true);
  // create some state to manage content
  const [content, setContent] = useState(null);

  // when the component is mounted preform some setup actions
  useEffect(() => {
    const setup = async () => {
      // do some setup actions, like fetching from an API
      const result = await fetch('https://jsonplaceholder.typicode.com/todos/1')
        .then(r => r.json());

      // update our state that manages content
      setContent(result);
      // when we are happy everything is ready show the user the content
      setIsLoading(false);
    };
    // run our setup function
    setup();
  }, [ ]);


  // if we are not yet ready to show the user data, show a loading message
  if (isLoading) {
    return (
      <div>
        <p>spinner goes in this div</p>
      </div>
    )
  }

  // when we are ready to show the user data is will be shown in this return statement
  return (
    <div>
      <p>this div will show when the `isLoading` state is true and do something with the content state is wanted</p>
    </div>
  )
}

I believe you'll find this more useful than the example you provided

CodePudding user response:

You already control state of fancyResult,
or you can use showSpinner state for only reason to show spinner

You can use for long progress Promise [Link] And Async/Await [Link]

const veryHardWork = async () => {
    setBackgroundColor("red");
    const awaiting = await new Promise((resolve, reject) => {
        for (let i = 0; i < 1000; i  ) {
            for (let j = 0; j < 1000; j  ) {
                resolve(console.log("So hard"));
            }
        }
    })
    // After Finished Awating Hardwork
    setFancyResult("done");
    setBackgroundColor("blue") ;
}


  return (
    <div style={{background: fancyResult === 'done' ? 'blue': 'red'}}>
      <button className="btn btn-primary" onClick={veryHardWork}></button>
      { fancyResult === 'done' && 'Show Spinner' }
    </div>
  )
  • Related