If you have ever tried to use window events in React, you will find that the state of the component inside the event is outdated, so here is what the component should look like in order to work, and an explanation of why this happens.

Here is our empty component with some imports, now we have to make it work.

import React, { useState, useLayoutEffect, useRef } from 'react'

	function MyComponent() {
	    return <div>Hi There</div>
	}

	export default MyComponent

Now, we need to add some hooks, **useLayoutEffect**is similar to _componentDidMount _(They both fire in the same phase of the component, read more about this hook here)

On the code below, I added the **_useLayoutEffect _**with our callback function inside, and it returns a cleanup function.

import React, { useState, useLayoutEffect, useRef } from 'react'

	function MyComponent() {
	  useLayoutEffect(() => {
	    function onWindowResize() {}
	    return () => {}
	  }, [])

	  return <div>Hi There</div>
	}

	export default MyComponent

#reactjs #development #react-hook #es6 #javascript #programming

How use window events in React and access current state inside callbacks
15.10 GEEK