Home > Software engineering >  REACT wait for useEffect to complete before rendering the UI
REACT wait for useEffect to complete before rendering the UI

Time:09-30

interface MyValue {
    //interface declaration
}
    
export function MyComponent {   
    const [myvalue, setMyvalue] = useState<MyValue>()
    
    useEffect(() => {
       setMyvalue(passedData)
    }, [passedData])
    
    function getAutofocus() {
        // return true/false based on myvalue value
    }
        
    render() {
       return (
          <div>
             <input
                autofocus={getAutofocus()}
                ref={c => (this._input = c)}
             />
          </div>
         );
       }
    }
 }

passedData is passed as a prop from parent and this is populated in the parent via a server GET call, which takes some time to resolve.

PROBLEM - getAutofocus() rendered before passedData is properly loaded.

my requirement here is to wait until passedData is properly resolved before invoking the getAutofocus() method. If we can stop the rendering of the UI/ or the input field until passedData is completely resolved, that will allow getAutofocus() to properly execute.

what's the best way to do this? can react suspense be used here?

CodePudding user response:

Sounds like conditional rendering would be enough to get what you need:

    render() {
       // if myvalue is not populated yet, do not render anything
       return !myvalue ? null : (
          <div>
             <input
                autofocus={getAutofocus()}
                ref={c => (this._input = c)}
             />
          </div>
         );
       }
    }

CodePudding user response:

The proper way of doing this is with a ref

const MyCom = props => {

const inputRef = React.useRef();

React.useEffect(()=>{
  if (inputRef.current) {
     inputRef.current.focus();
}

},[inputRef]);

return (
          <div>
             <input
                ref={inputRef}
             />
          </div>
         );
}

Remove render method only class components have render

  • Related