I'm using useState
hook in a custom hook.
I'm calling the setValue
function that is returned from the useState
twice:
1) After an onChange event
2) After the component was notified of a change from the server.
The flow of events is:
- onChange event (in the component) triggers
setValue
= rerender - I'm using a
useEffect
(=after rerender) hook to update the server of the change - API function is called to update the server - I have a custom service which receives the server's response and notifies the component
- When notified the component calls
setValue
again but in this case, the value is the same so no need to rerender.
My problem is the component gets rerendered after it was notified of the changes even though the value received is the same.
My code:
Gain Component
import * as React from 'react';
import { useDSPParamUpdate } from '../../../Hooks/useDSPParamUpdate';
import { ControlParamProps } from '../..';
const Gain = (props: ControlParamProps) => {
let min: number = 0;
let max: number = 0;
const { paramId, controlId } = props;
const { param, value, setValue } = useDSPParamUpdate({ controlId, paramId })
if (param && param.range && param.range.length >= 2) {
min = param.range[0];
max = param.range[1];
}
/*calls the setValue from the hook*/
const handleChange = (event: any) => {
const newValue = event.target.value;
setValue(newValue);
}
return (
<div className="gain">
{max}
<input className="dsp-action range-vertical" type="range"
min={min}
max={max}
value={value}
onChange={handleChange} />
{min}
</div>
);
}
export default Gain;
useDSPParamUpdate - custom hook
import * as React from 'react';
import { ControlParamProps } from '../dsp';
import { dspService } from '../../core/services/dsp.service';
export function useDSPParamUpdate(props: ControlParamProps) {
const initValue = ...
const [value, setValue] = React.useState(initValue);
function updateDevice() {
// calls some API func to update the server (sends the value)
}
// subscribes to server changes
React.useEffect(() => {
// subscribrs to server notifications
let unsubscribe = dspService.subscribe((newVal) => setValue(newVal));
return () => {
unsubscribe();
};
}, []);
// sends data to the server after update
React.useEffect(() => {
updateDevice();
}, [value]);
return { param, value, setValue };
}