Skip to content Skip to sidebar Skip to footer

Display Value Saved In Useref Variable

I have a variable const prediction = useRef(null); I click on a button that runs a function which sets the value of my variable: function showResult() { cla

Solution 1:

A ref changing its current value does not trigger any re-renders in React components, but you should be able to replace the snippets above and trigger the re-render to see the latest value:

const prediction = useRef<any>(null);

Becomes:

const [prediction, setPrediction] = useState(null);

The getResult function would then look like:

functiongotResult() {
    classifier.current.classify(capture, (err: any, result: any) => {
        setPrediction(result[0].label])
    });
}

Finally the rendering:

return (
    <div><Buttonvariant="contained"color="primary"onClick={() => gotResult()}>Test!</Button><br /><span>Prediction: {prediction}</span><br /></div>
)

Your classifier is setting the current value on every render. You probably only want that whenever featureExtractor, capture or videoReady changes. You can do that with useMemo:

const classifier = useMemo(() => {
    return featureExtractor.classification(capture, videoReady);
}, [featureExtractor, capture, videoReady]);

That dependency array in useMemo will make sure the classifier only gets defined if those variables change and not on every render.

Post a Comment for "Display Value Saved In Useref Variable"