score:1
You are not only missing data
from the dependency array of useEffect
hook but you are also missing setConnections()
function from the dependency array.
You can use useReducer
hook to move the state update logic out of the useEffect
hook.
const initialState = {
data: { foo: [], bar: [] },
connections: ["conn1", "conn2"]
}
const reducerFunc = (state, action) => {
switch(action.type) {
case 'UPDATE_CONNECTIONS':
let _tempConns = [...action.checkedFields];
let _conns = [];
_tempConns.forEach(tempConn => {
if (state.data[tempConn] !== undefined) _conns.push(`update_${tempConn}`);
else _conns.push(tempConn);
});
return { ...state, connections: _conns };
default:
return state;
}
};
const [myState, dispatch] = useReducer(reducerFunc, initialState);
const { checkedFields } = useContext(FieldContext); // ["foo", "moo"];
useEffect(() => {
dispatch({ type: 'UPDATE_CONNECTIONS', payload: checkedFields });
}, [checkedFields]);
Since React makes sure that dispatch
function won't change, you can omit it from useEffect
hook's dependency array.
For details on how to use useReducer
hook, see folowing links:
score:0
With your update, it seems that your socket never close. If your component unmount / remount, you add a new socket on background. And then on every updates, it fire all previous sockets.
Your socket hook should return a close socket function. (I guess, I never use socket directly)
useEffect(() => {
const _socket = io(WS_URI);
_socket.on("info", data => {
// some magic happens here to add to the `data` object which is not important for this question
});
setSocket(_socket);
return () => {_socket.close();}
}, [])
(That's not the response of your answer but it can help :) )
score:1
Could try with useRef
if you can get away with the following in your websocket and there are no other useEffect
s counting on the data
reference
useRef returns a mutable ref object whose .current property is initialized to the passed argument (initialValue). The returned object will persist for the full lifetime of the component.
// make `data` a ref object
// Pitfall: any changes to `data.current` will NOT be tracked
const data = useRef({ foo: [], bar: [] })
// the websocket hook
useEffect(() => {
...
_socket.on("info", data => {
...
// update properties on `data.current`
data.current.foo = 'some new value'
data.current.bar = 'anoher new value;
});
...
}, [])
useEffect(() => {
setConnections(prevConnections => {
...
// reference data value from data.current
const data = data.current
...
return _conns;
});
}, [checkedFields])
Source: stackoverflow.com
Related Query
- Use useState value in useEffect without making the state update useEffect
- React: Execute function in useEffect Hook to update state. Use the state value to return component A or B
- How do I use the spread operator to update a state value in React?
- React - How to update the state in useEffect without causing an infinite loop?
- How to set the initial value of useState with the value of another state set in a useEffect hook?
- I use useState hock to store the value but it did not update
- React setState and use the value to update another state
- How to use useState hook with array state for children that call the setter function without infinite rendering loop?
- How to use state to update the value of variable in the button value property?
- how to update the state if dropdown has selected value with Hooks and useState
- How to get the changed (new) state value in React JS function with / without useEffect hook?
- Why cant I take a value from the current state and use that inside of my useState hook?
- Cannot get the updated the state value useState and UseEffect
- React, how to update a state without repainting, or how to trigger useEffect without useState (and with useRef), or how to stop infinite loop
- console log the state after using useState doesn't return the current value
- How can I access state in an useEffect without re-firing the useEffect?
- useState in useEffect does not update state
- Better way to use useState hook for setting the boolean state in React
- Why does calling useState's setter with the same value subsequently trigger a component update even if the old state equals the new state?
- How to trigger a state update without triggering it’s useEffect
- useState updates state value but is passing the old value as an argument to a function
- How does calling "setState" as a callback in a function, without any new state value, successfully update the state?
- How to update the unmount handler in a useEffect without firing it repeatedly?
- How to update state with the useState hook
- how to delete all data and the update the page without refreshing using useEffect
- How to update the correct state value in a parent component that gets its value from a child component using hooks in react?
- Redux Reducer - How to update an object value without mutating the state?
- Will React trigger state update if new provided value is the same?
- Firebase: HowTo update the value item of a record without knowing its unique id?
- ReactJS useState hook: Can I update array of objects using the state variable itself?
More Query from same tag
- React Router don't pass value to match.props
- How to cleanup this fetchEvent function used in a useEffect hook?
- How to make React and Meteor fit together
- Create-React-App adding folders inside src 'Module not found: can't resolve'
- React, createContext default value problem with useState hook
- Updating component data in React
- Is It Possible To Trigger Contained Component's render from within the Container in React?
- How to execute an action after the first one is resolved in saga?
- Image sizing not consistent in different browsers
- How to centralize an icon and a paragraph in one line
- React handleClick in parent
- In React Native, How Can I Use KeyboardAvoidingView with a Modal in iOS?
- Does iOS has In App updates like feature as of Android?
- Having trouble testing check box on change within CardHeader Avatar={}
- Typescript eslint disable no-unused-vars
- Is there a way to iterate through a timer in React?
- Replace elements in html with custom react components
- Calling a function inside render function - ReactJS?
- Not all date data shows on x axis line chart
- React router Link not causing component to update within nested routes
- Axios/Backend in React stops working after a while with no error
- How to Redirect http to https in ReactJs
- Core UI Admin - External sorter icon not shown React js
- Enzyme mount does not render anything
- Can someone explain to me what the correct way to pass the data is?
- material-ui table not displaying data
- how to put div below header div and above footer div with full height html
- Matched leaf route at location
- JHipster - execute code after function is finished
- How to enable/add anchor tag to the string in ReactJS?