Search code examples
reactjstypescriptreact-hooksuse-effectreact-component

REACT wait for useEffect to complete before rendering the UI


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?


Solution

  • 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>
             );
           }
        }