score:1
The solution to your problem could look as follows:
First create a custom usePrevious
hook. This is just another function which uses the new useRef
method to store the previous scroll value and only updates it when a new value is passed to it.
// Hook
function usePrevious(value) {
// The ref object is a generic container whose current property is mutable ...
// ... and can hold any value, similar to an instance property on a class
const ref = useRef();
// Store current value in ref
useEffect(() => {
ref.current = value;
}, [value]); // Only re-run if value changes
// Return previous value (happens before update in useEffect above)
return ref.current;
}
In the actual component we declare a previousPosition
variable. Every time the component re-renders, the our customHook is executed with the current position. It returns the previous position which then gets assigned.
Also with each render, the useEffect
method is being executed, as we do not pass an Array as second argument. There we just compare the current scroll position with
the previous and scroll back to the previous in case it changed.
function Scroll(props){
const prevPosition = usePrevious(window.pageYOffset);
// Update scoll position with each update
useEffect(() => {
if(window.pageYOffset !== prevPosition){
window.scrollTo(0, prevPosition);
}
});
return (
<div>
...
</div>
);
}
score:1
If I understand correctly, use useLayoutEffect
instead of useEffect
. This will scroll back to the top before the component is rendered. Remember to add the dependency array.
Source: stackoverflow.com
Related Query
- Restore scroll position in React Hooks with useRef is shaky
- Restore scroll position after toggled a modal in react with useContext
- Adding new DOM items with React in Chrome does not keep expected scroll position
- React scroll to top on page refresh - don't restore position
- Scroll to y location within react element with useRef
- Scroll to element on page load with React Hooks
- Cannot position react-perfect-scrollbar with scrollTop using React hooks
- Restore form submission state after failed submission with react hooks
- React Hooks - "Function components cannot be given refs" with useRef
- How to go to another page without keeping scroll position with React
- Logging scroll position on scroll using React hooks
- How to use React Infinite Scroll with hooks
- React Hooks useState() with Object
- Get current scroll position of ScrollView in React Native
- Handle an input with React hooks
- React Function Components with hooks vs Class Components
- Reset to Initial State with React Hooks
- Wrong React hooks behaviour with event listener
- Testing React Functional Component with Hooks using Jest
- How to implement Error Boundary with React Hooks Component
- How target DOM with react useRef in map
- How to focus something on next render with React Hooks
- How to mock history.push with the new React Router Hooks using Jest
- Get scroll position with Reactjs
- How to use React useRef hook with typescript?
- Firebase listener with React Hooks
- Change the cursor position in a textarea with React
- Is it possible to use react-datepicker with react hooks forms?
- Is there any way to see names of 'fields' in React multiple state with React DevTools when using 'useState' hooks
- React - useRef with TypeScript and functional component
More Query from same tag
- How Do I Redirect My Frontend React Application From External API Call
- Uncaught ReferenceError: global is not defined at Object../node_modules/fbjs/lib/setImmediate.js
- TypeScript - How to splite react context with dispatch actions?
- Unable to render a view onPress TouchableOpacity in react native
- Calendar Ant Design: How to show events with variable dates?
- React Redux cant get reducer to pick up actions
- How to redirect to a different page after a redux action using react
- I'm having trouble loading an .svg image in react using styled components. Can anyone tell me why its not loading?
- React saving array state using hooks
- Storybook override import method
- ReactJS error You may need an appropriate loader to handle this file type
- React - second layer of object in list is undefined
- React - Importing non-modular sass file returns empty object
- Using local storage in ReactJS
- React Hooks and React Query (useQuery): invoking the API call/ query only when a button is clicked
- How to use a TypeScript cast with JSX/TSX
- How to pass props to Bootstrap OverlayTrigger overlay component?
- react <i> tag onClick triggers only after double Click
- Modal component - onClick event
- How to remove duplicate Ant Design components across chunks
- React JS grouping a cart
- Two way communication between two functional React JS components
- Stack with style in react js
- Load local images in React.js
- How to export hooks to other functions in react.js?
- array of object is not rendering in react js
- p5.js mousePressed event returns Undefined
- React Context - setState with onClick inside Consumer
- Video Conferencing like video grid using css grid
- React hooks callback receives outdated state