score:0
this is tricky but trivial for lots of projects. your useeffect will be trigged one time and the function inside will be trigged everytime the user resize the browser.
sometimes when you resize the browser you cannot access state or set the state (using usestate) so i like to put the value of the width
of the window outside. this way i can reuse the values anytime with almost no conflicts.
// react using hooks
import { usestate, useeffect } from 'react';
// use outside the component
let ismobile = true; // variable to check width
const mycomponent = () => {
// optional: save the width of the window using state
const [width, setwidth] = usestate(window.innerwidth); // check width size of the window
const handlewindowsizechange = () => {
setwidth(window.innerwidth);
ismobile = window.innerwidth < 700 ? true : false;
};
// call your useeffect
useeffect(() => {
window.addeventlistener('resize', handlewindowsizechange);
return () => {
window.removeeventlistener('resize', handlewindowsizechange);
};
}, []);
// view of the component
return (<h1>{ismobile}</h1>)
}
score:0
you want to use useeffect
to add the event listener (and remove it).
const handleresize = () => {
...
}
react.useeffect(() => {
window.addeventlistener('resize', handleresize)
return () => window.removeeventlistener('resize', handleresize)
}, [])
this will add the event listener when the component is rendered, and remove it when it's not (the return value of useeffect
is run on cleanup). useeffect
will run every time a variable in the array in the second parameter changes (in this case it's left as empty [], so it will only run once).
also, instead of using settimeout, you should consider using a "debounced" function, this post explains how they work. you can find debounce functions to reuse on npm and in lodash etc.
score:0
you should actually use uselayouteffect
to handle this kind of computation, because it is triggered while the component renders (after the computation is done, but before the painting is done), as opposed to useeffect, that runs after the component has rendered.
Source: stackoverflow.com
Related Query
- How to call useEffect when browser is resized
- React useEffect calls API too many time, How can I limit the API call to only once when my component renders?
- How to call UseEffect when data comes into material table?
- How to fix missing dependency warning when using useEffect React Hook
- How to call loading function with React useEffect only once
- react native how to call multiple functions when onPress is clicked
- ReactJS: how to call useEffect hook only once to fetch API data
- How can I call methods on Reactjs components in the browser console or from an outside script?
- How do you call fitBounds() when using leaflet-react?
- How do I simulate browser events when writing tests for React js?
- React: How does React make sure that useEffect is called after the browser has had a chance to paint?
- how and when to call a react component methods after state change from redux
- How to prevent useCallback from triggering when using with useEffect (and comply with eslint-plugin-react-hooks)?
- How redirect to login page when got 401 error from ajax call in React-Router?
- How do you get any useful call stack information when debugging react native?
- React: how can I call a function when a component has loaded?
- How to log out all tabs in one browser when one tab is logged out in React.js?
- How to wait for in browser JSX compiler before call to render component
- Invalid hook call. Hooks can only be called inside of the body of a function component when i call useQuery in useEffect
- CORS error when making network call in useEffect in Next.Js
- How to rerun useEffect when page is visible?
- How to cleanup useEffect correctly when using history.push?
- How to await a setState call finishing when using useState hook that immediately needs that state to make an API call?
- How to output eslint errors in the browser when using reactjs
- How to only run useEffect when something was added to array with React?
- How to useEffect when value in localStorage changed?
- How to fix TypeScript error occurs when call takeEvery() in redux-saga?
- How to update my useEffect hook when State change happen in a different .js file's component in ReactJS?
- How to detect server data changes without refreshing browser or using useEffect in React?
- How to call react logger function when using CDN
More Query from same tag
- How can I create a React component with a variable?
- useEffect infinite loop occurs only while testing, not otherwise - despite using useReducer
- Is there a way to write a custom react hook that can injected into a component?
- Unable to pass props
- What is the expected return of `useEffect` used for?
- ReactJS+ Antd - pagination dynamic row expand issue
- I am trying to build contact form using React and Express and it isn't working
- how to redirect to home page after login: ReactJS?
- How to navigate to a new page in react?
- Unmounting a Component with a SetInterval in React
- When returning content from getInitialProps, is there a method to check for empty?
- React PropTypes.array has keys with type string
- Strategies to implementing a conditional Navbar if a user is logged in or not
- export 'withRouter' (imported as 'withRouter') was not found in 'react-router-dom'
- How to prevent a whole list from re-rendering when editing an element on the list?
- When I click on Tab more than once the back button works incorrectly
- React onClick JSX returned from function
- Modifying default configuration for react app
- Is it a good practice to have config in Redux store?
- In React.js, Wrong clientHeight Got When Use flexGrow
- Generic component with default type
- how to execute a .js file containing multiple functions, via react jsx
- How do I dynamically toggle multiple layers in Deck.gl?
- how to re-use react callback for lifting state up?
- React Child Component In Different Part of DOM
- Functional component props/state/store not updated in function - what's a viable alternative?
- Image not showing in react-draft-wysiwyg editor using draft js
- Getting days difference between two dates in React.js
- React Router / Redux / HOC not working with 'render' prop
- Next.js static site generation, why is getStaticProps params empty?