score:0
a colleague came with this solution. using a reference for which as it is a reference is not enclosed.
const usesocketamountreceivedstate = (event: string): number => {
const count = useref(0);
const [state, setstate] = usestate(0);
useeffect(() => {
socket.on(event, () => {
count.current++;
setstate(count.current);
});
return (): void => {
socket.off(event);
};
}, []);
return state;
}
score:2
try putting an empty array as the second argument in the hook. you don't want this to register an event each time the component renders.
const usesocketamountreceivedstate = (event: string): number => {
const [total, settotal] = usestate(0);
useeffect(() => {
socket.on(event, () => {
console.log(total);
settotal(total + 1);
});
return (): void => {
socket.off(event);
};
}, [total]);
return total;
}
update:
i made an update to my initial answer, and added total into the dependency array of the react hook.
note that the second argument, aka dependency array. it is an array that accepts state or prop. and it instructs react to run this hook each time any of the elements in the dependency array changes.
if you pass an empty array, then the hook will only be run at initial load, after the component mounts.
in your example, if you pass an empty array, it creates a closure. hence, the total value will always be the initial value.
so you can pass total into the dependency array, which will invoke the useeffect() to run only when total value changes. in your example, where there is no dependency array passed to the second argument, the useeffect() will run every single time, which is not what we want.
score:2
socket.on event has to be outside the useeffect function
const usesocketamountreceivedstate = (event: string): number => {
const [total, settotal] = usestate(0);
socket.on(event, () => {
console.log(total);
settotal(total + 1);
});
useeffect(() => {
return (): void => {
socket.off(event);
};
}, []);
return total;
}
Source: stackoverflow.com
Related Query
- Keep state in sync with fast occuring events
- How to keep the React state in sync with MySQL database
- Keep getter function in sync with an object's current state in React/TypeScript
- Redux: Can't figure out why ownProps gets out of sync with state
- ReactJS - How can I implement pagination for react with keep state when route change?
- Sync queryParameters with Redux state and react router for function components
- How to sync React Router Params with state
- Material UI Autocomplete: Sync value with state
- How do I keep App() level state from resetting with react-router-dom in React.js?
- redux with router keep state when changing url
- redux store out of sync store().getState() with state from redux logger
- What's the idiomatic way to keep UI in sync with ajax calls when using Flux?
- How to keep sync validation with Redux-form v6 while implementing custom onBlur?
- I want to sync google calendar events after login with google javascript
- Async/await with sync func changing react state
- ReferenceError: window is not defined, when trying to sync the search input state with react instant search
- Keep URL and state when working with filter drop-downs using react hook
- How do I sync my search state with Url and connect it to next.js router?
- How can I setup my Redux Initial state as an Object, and then properly sync it with my reducer functions?
- how to sync the antd multiple select table checkbox state with a select option
- How to keep state property's value beyond component's parent updates with react hooks?
- react/redux state and components useState become out of sync on fast clicking
- How can I keep the state from reseting even after I change the url with Router?
- How to have conditional elements and keep DRY with Facebook React's JSX?
- Does React keep the order for state updates?
- Executing async code on update of state with react-hooks
- How to sync props to state using React hooks : setState()
- React input defaultValue doesn't update with state
- Reset to Initial State with React Hooks
- react.js custom events for communicating with parent nodes
More Query from same tag
- React and Redux: Dispatching all actions within one function
- React: 404/No folder structure after running `npm run build`
- Cannot render const in a react component
- Why the value in this array (apparently) changes immediately
- React.js - Implementing sorting of components
- React/Javascript Comparison Operator Not Working
- how to test radio button in react testing library(User can select other radio button)
- this.props.fetch is not a function redux
- how can i pass functional react component to a function?
- Unable to grab element by className even if I see it in the browser console
- setState not updating state with multiple varaibles
- Do Examples of "Scroll Loading" with FlatList Exist?
- File Limitation in express server (Bigger than 50MB)
- React Redux Firebase - isLoaded only false for the first document when using firestore
- React "useViewBox" hook for SVG viewBox failing ESLint rule exhaustive-deps
- Is it a good pattern to save react element in the useState for good perfomance?
- React - put html tags inside json content
- Map to element position with pure css
- React state doesn't work, it doesn't rerender components
- How can I toggle all checkboxes with useState?
- ComponentDidMount() not firing
- Delay load on every page with reach-router
- Warning: Failed prop type: Invalid prop `tag` supplied to `NavLink`
- Server side rendering React components that loads state through Ajax
- Cannot write into the input field in React App
- React Modal returns last value of mapped data
- Form validation test on submit with mock data
- How to unit test an array as a prop using react-testing-library
- Unresolved variable WebStorm this.props
- Get specific property name in an object