Consistent useCallback implementation in ReactDOMServer (#18783)
Alex Taylor committed
Apr 29, 2020 at 16:22 UTC
e71f5df9c32b3b486bf4efce861834389c395d47
2 files changed
+30
-3
packages/react-dom/src/__tests__/ReactDOMServerIntegrationHooks-test.js
+29
-1
@@ -564,7 +564,7 @@ describe('ReactDOMServerHooks', () => {
564
});
565
566
describe('useCallback', () => {
567
- itRenders('should ignore callbacks on the server', async render => {
567
+ itRenders('should not invoke the passed callbacks', async render => {
568
function Counter(props) {
569
useCallback(() => {
570
yieldValue('should not be invoked');
@@ -589,6 +589,34 @@ describe('ReactDOMServerHooks', () => {
589
expect(domNode.tagName).toEqual('SPAN');
590
expect(domNode.textContent).toEqual('Count: 5');
591
});
592
+
593
+ itRenders(
594
+ 'should only change the returned reference when the inputs change',
595
+ async render => {
596
+ function CapitalizedText(props) {
597
+ const [text, setText] = useState(props.text);
598
+ const [count, setCount] = useState(0);
599
+ const capitalizeText = useCallback(() => text.toUpperCase(), [text]);
600
+ yieldValue(capitalizeText);
601
+ if (count < 3) {
602
+ setCount(count + 1);
603
+ }
604
+ if (text === 'hello' && count === 2) {
605
+ setText('hello, world.');
606
+ }
607
+ return <Text text={capitalizeText()} />;
608
+ }
609
+
610
+ const domNode = await render(<CapitalizedText text="hello" />);
611
+ const [first, second, third, fourth, result] = clearYields();
612
+ expect(first).toBe(second);
613
+ expect(second).toBe(third);
614
+ expect(third).not.toBe(fourth);
615
+ expect(result).toEqual('HELLO, WORLD.');
616
+ expect(domNode.tagName).toEqual('SPAN');
617
+ expect(domNode.textContent).toEqual('HELLO, WORLD.');
618
+ },
619
+ );
620
});
621
622
describe('useImperativeHandle', () => {
packages/react-dom/src/server/ReactPartialRendererHooks.js
+1
-2
@@ -456,8 +456,7 @@ export function useCallback<T>(
456
callback: T,
457
deps: Array<mixed> | void | null,
458
): T {
459
- // Callbacks are passed as they are in the server environment.
460
- return callback;
459
+ return useMemo(() => callback, deps);
460
}
461
462
function useResponder(responder, props): ReactEventResponderListener<any, any> {