Skip to content

Commit

Permalink
Add consumers state slicing optimizations to example
Browse files Browse the repository at this point in the history
  • Loading branch information
Dmitry Dushkin committed May 9, 2019
1 parent 9975f4a commit e76a71e
Show file tree
Hide file tree
Showing 3 changed files with 41 additions and 15 deletions.
48 changes: 36 additions & 12 deletions example/example.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -8,7 +8,9 @@ function ItemScreen() {
<Provider initialState={defaultState}>
<Item />
<hr />
<ItemTestMemo />
<MethodsConsumerNoRerendering />
<hr />
<StateSlice />
</Provider>
);
}
Expand All @@ -28,20 +30,42 @@ function Item() {
);
}

let itemTestRerenderCounter = 0;
const ItemTestMemo = memo(ItemTest);
function ItemTest() {
let methodsConsumerRerenderingCounter = 0;
function MethodsConsumerNoRerendering() {
const { methods } = useItemsStore();
const handleLoadClick = useMemo(() => loadItem(methods), []);

return (
<div>
<p>
This component using only methods and should not be re-rendered ever
</p>
<p>{`Rerender counter: ${itemTestRerenderCounter++}`}</p>
<button onClick={handleLoadClick}>Load item from memo component</button>
</div>
return useMemo(
() => (
<div>
<p>
This component using only methods and should not be re-rendered ever
</p>
<p>{`Rerender counter: ${methodsConsumerRerenderingCounter++}`}</p>
<button onClick={handleLoadClick}>Load item from memo component</button>
</div>
),
[]
);
}

let stateSliceRerenderingCounter = 0;
function StateSlice() {
const {
state: { error },
methods
} = useItemsStore();
return useMemo(
() => (
<div>
<p>This component rerenders only on error occurance</p>
<p>{`Rerender counter: ${stateSliceRerenderingCounter++}`}</p>
<button onClick={loadItem(methods)}>
Load item from memo component
</button>
</div>
),
[error]
);
}

Expand Down
2 changes: 1 addition & 1 deletion example/store.ts
Original file line number Diff line number Diff line change
@@ -1,6 +1,6 @@
// item-store.ts
import { createUseStore, Thunk } from "../src/create-store";
import { useState } from "react";
import { useState, useMemo } from "react";
import createUseContext from "constate";

const pause = async (timeout: number): Promise<any> =>
Expand Down
6 changes: 4 additions & 2 deletions src/create-store.ts
Original file line number Diff line number Diff line change
Expand Up @@ -67,6 +67,8 @@ export const createUseStore = <S extends any, M extends MethodsIn<S>>(
defaultState: S,
methodsIn: M
) =>
createUseContext(({ initialState }: { initialState: S }) =>
useMethods(initialState || defaultState, methodsIn)
createUseContext(
({ initialState }: { initialState: S }) =>
useMethods(initialState || defaultState, methodsIn),
({ state }) => [state]
);

0 comments on commit e76a71e

Please sign in to comment.