Skip to content

Commit

Permalink
Ensure state updates work in signals (#4560)
Browse files Browse the repository at this point in the history
  • Loading branch information
JoviDeCroock authored Nov 21, 2024
1 parent 68ada1a commit 0fc547c
Show file tree
Hide file tree
Showing 2 changed files with 47 additions and 7 deletions.
10 changes: 4 additions & 6 deletions hooks/src/index.js
Original file line number Diff line number Diff line change
Expand Up @@ -249,7 +249,7 @@ export function useReducer(reducer, initialState, init) {
// We check whether we have components with a nextValue set that
// have values that aren't equal to one another this pushes
// us to update further down the tree
let shouldUpdate = false;
let shouldUpdate = hookState._component.props !== p;
stateHooks.forEach(hookItem => {
if (hookItem._nextValue) {
const currentValue = hookItem._value[0];
Expand All @@ -259,11 +259,9 @@ export function useReducer(reducer, initialState, init) {
}
});

return shouldUpdate || hookState._component.props !== p
? prevScu
? prevScu.call(this, p, s, c)
: true
: false;
return prevScu
? prevScu.call(this, p, s, c) || shouldUpdate
: shouldUpdate;
}

currentComponent.shouldComponentUpdate = updateHookState;
Expand Down
44 changes: 43 additions & 1 deletion hooks/test/browser/useState.test.js
Original file line number Diff line number Diff line change
@@ -1,5 +1,5 @@
import { setupRerender, act } from 'preact/test-utils';
import { createElement, render, createContext } from 'preact';
import { createElement, render, createContext, Component } from 'preact';
import { useState, useContext, useEffect } from 'preact/hooks';
import { setupScratch, teardown } from '../../../test/_util/helpers';

Expand Down Expand Up @@ -371,4 +371,46 @@ describe('useState', () => {
rerender();
expect(scratch.innerHTML).to.equal('<p>hello world!!!</p>');
});

describe('Global sCU', () => {
let prevScu;
before(() => {
prevScu = Component.prototype.shouldComponentUpdate;
Component.prototype.shouldComponentUpdate = () => {
return true;
};
});

after(() => {
Component.prototype.shouldComponentUpdate = prevScu;
});

it('correctly updates with multiple state updates', () => {
let simulateClick;

let renders = 0;
function TestWidget() {
renders++;
const [saved, setSaved] = useState(false);

simulateClick = () => {
setSaved(true);
setSaved(false);
};

return <div>{saved ? 'Saved!' : 'Unsaved!'}</div>;
}

render(<TestWidget />, scratch);
expect(scratch.innerHTML).to.equal('<div>Unsaved!</div>');
expect(renders).to.equal(1);

act(() => {
simulateClick();
});

expect(scratch.innerHTML).to.equal('<div>Unsaved!</div>');
expect(renders).to.equal(2);
});
});
});

0 comments on commit 0fc547c

Please sign in to comment.