Q:

How to trigger the useCallback in React

I am having a React(version used 16.8) component, I have a const updateDiffText = useCallback(() callback on click of anchor GENERATE DIFF onclick onClick={updateDiffText} I call call back this updateDiffText
My requirement is I don't want one anchor code in my UI, I want whenever I have oldText and newText It should trigger the method updateDiffText and show the result. User should not click on anchor link to perform this.
My Code sand box here -  https://codesandbox.io/s/react-diff-view-demo-htp06
if I have values in oldtext and newText it should call updateDiffText this method
My Code -
const DiffViewer = props => {
    const oldText = useInput(props.startupConfigData);
    const newText = useInput(props.runningConfigData);
    const [{ type, hunks }, setDiff] = useState("");
    const updateDiffText = useCallback(() => {
        const diffText = formatLines(diffLines(oldText.value, newText.value), {
            context: 3
        });
        const [diff] = parseDiff(diffText, { nearbySequences: "zip" });
        setDiff(diff);
    }, [oldText.value, newText.value, setDiff]);

    const tokens = useMemo(() => tokenize(hunks), [hunks]);

    return (
        <div style={{ height: "450px", overflow: "auto" }}>
            <a href="#" onClick={updateDiffText}>
                GENERATE DIFF
            </a>

            {setDiff ? (
                <Diff
                    viewType="split"
                    diffType={type}
                    hunks={hunks || EMPTY_HUNKS}
                    tokens={tokens}
                >
                    {hunks => hunks.map(hunk => <Hunk key={hunk.content} hunk={hunk} />)}
                </Diff>
            ) : (
                ""
            )}
        </div>
    );
};

Let me know if query is not clear. Thanks.

A:

Try to use the useEffect instead of useCallback. In your case you are are not calling the memoized function in the render stage. useCallback will return a memoized function. Check the modified version.

https://codesandbox.io/s/react-diff-view-demo-izdyi

