Skip to content

new API with useMutableSource #48

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Merged
merged 28 commits into from
Dec 18, 2020
Merged
Show file tree
Hide file tree
Changes from 7 commits
Commits
Show all changes
28 commits
Select commit Hold shift + click to select a range
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
4 changes: 2 additions & 2 deletions .eslintrc.json
Original file line number Diff line number Diff line change
Expand Up @@ -22,7 +22,7 @@
"react-hooks/rules-of-hooks": "error",
"react-hooks/exhaustive-deps": ["error", { "additionalHooks": "useIsomorphicLayoutEffect" }],
"@typescript-eslint/explicit-function-return-type": "off",
"@typescript-eslint/no-empty-interface": "off",
"@typescript-eslint/no-explicit-any": "off",
"react/jsx-filename-extension": ["error", { "extensions": [".js", ".tsx"] }],
"react/prop-types": "off",
"react/jsx-one-expression-per-line": "off",
Expand All @@ -31,7 +31,7 @@
"import/no-unresolved": ["error", { "ignore": ["reactive-react-redux"] }],
"no-param-reassign": "off",
"no-plusplus": "off",
"prefer-object-spread": "off",
"no-bitwise": "off",
"default-case": "off"
},
"overrides": [{
Expand Down
199 changes: 105 additions & 94 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -30,16 +30,19 @@ Most likely, `useTrackedState` performs better than

Technically, `useTrackedState` has no [stale props](https://react-redux.js.org/api/hooks#stale-props-and-zombie-children) issue.

### 2. state-based object for context value
### 2. useMutableSource without Context

react-redux v7 uses store-based object for context value,
while react-redux v6 used to use state-based object.
Using state-based object naively has
[unable-to-bail-out issue](https://github.com/facebook/react/issues/14110),
but this library uses state-based object with
undocumented function `calculateChangedBits`
to stop propagation of re-renders.
See [#29](https://github.com/dai-shi/reactive-react-redux/issues/29) for details.
react-redux v7 has APIs around Context.
This library is implemented with useMutableSource,
and it patches the Redux store.
APIs are provided without Context.
It's up to developers to use Context based on them.
Check out `./examples/11_todolist/src/context.ts`.

There's another difference from react-redux v7.
This library directly use useMutableSource, and requires
useCallback for the selector in useSelector.
[equalityFn](https://react-redux.js.org/api/hooks#equality-comparisons-and-updates) is not supported.

## How tracking works

Expand All @@ -62,8 +65,7 @@ npm install reactive-react-redux
import React from 'react';
import { createStore } from 'redux';
import {
Provider,
useDispatch,
patchStore,
useTrackedState,
} from 'reactive-react-redux';

Expand All @@ -81,11 +83,11 @@ const reducer = (state = initialState, action) => {
}
};

const store = createStore(reducer);
const store = patchStoroe(createStore(reducer));

const Counter = () => {
const state = useTrackedState();
const dispatch = useDispatch();
const state = useTrackedState(store);
const { dispatch } = store;
return (
<div>
{Math.random()}
Expand All @@ -99,8 +101,8 @@ const Counter = () => {
};

const TextBox = () => {
const state = useTrackedState();
const dispatch = useDispatch();
const state = useTrackedState(store);
const { dispatch } = store;
return (
<div>
{Math.random()}
Expand All @@ -113,113 +115,122 @@ const TextBox = () => {
};

const App = () => (
<Provider store={store}>
<>
<h1>Counter</h1>
<Counter />
<Counter />
<h1>TextBox</h1>
<TextBox />
<TextBox />
</Provider>
</>
);
```

## API

This library exports four functions.
The first three `Provider`, `useDispatch` and `useSelector` are
compatible with [react-redux hooks](https://react-redux.js.org/api/hooks).
The last `useTrackedState` is unique in this library.
<!-- Generated by documentation.js. Update this documentation by updating the source code. -->

### Provider
### patchStore

This is a provider component.
Typically, it's used closely in the app root component.
patch Redux store for React

```javascript
const store = createStore(...);
const App = () => (
<Provider store={store}>
...
</Provider>
);
```
#### Parameters

### useDispatch
- `store` **Store&lt;State, Action>**

This is a hook that returns `store.dispatch`.
#### Examples

```javascript
const Component = () => {
const dispatch = useDispatch();
// ...
};
import { createStore } from 'redux';
import { patchStore } from 'reactive-react-redux';

const reducer = ...;
const store = patchStore(createStore(reducer));
```

### useSelector

This is a hook that returns a selected value from a state.
This is compatible with react-redux's useSelector.
It also supports [equalityFn](https://react-redux.js.org/api/hooks#equality-comparisons-and-updates).
useSelector hook

selector has to be stable. Either define it outside render
or use useCallback if selector uses props.

#### Parameters

- `patchedStore` **PatchedStore&lt;State, Action>**
- `selector` **function (state: State): Selected**

#### Examples

```javascript
const Component = () => {
const selected = useSelector(selector);
// ...
import { useCallback } from 'react';
import { useSelector } from 'reactive-react-redux';

const Component = ({ count }) => {
const isBigger = useSelector(store, useCallack(state => state.count > count, [count]));
...
};
```

### useTrackedState

This is a hook that returns a whole state wraped by proxies.
It detects the usage of the state and record it.
It will only trigger re-render if the used part is changed.
There are some [caveats](#caveats).
useTrackedState hook

It return the Redux state wrapped by Proxy,
and the state prperty access is tracked.
It will only re-render if accessed properties are changed.

#### Parameters

- `patchedStore` **PatchedStore&lt;State, Action>**
- `opts` **Opts** (optional, default `{}`)

#### Examples

```javascript
import { useTrackedState } from 'reactive-react-redux';

const Component = () => {
const state = useTrackedState();
// ...
const state = useTrackedState(store);
...
};
```

### trackMemo
## Recipes

This is used to explicitly mark a prop object as used
in a memoized component. Otherwise, usage tracking may not
work correctly because a memoized component doesn't always render
when a parent component renders.
### Context

```javascript
const ChildComponent = React.memo(({ num1, str1, obj1, obj2 }) => {
trackMemo(obj1);
trackMemo(obj2);
// ...
});
```
You can create Context based APIs like react-redux v7.

### getUntrackedObject
```typescript
import { createContext, createElement, useContext } from 'react';
import {
PatchedStore,
useSelector as useSelectorOrig,
useTrackedState as useTrackedStateOrig,
} from 'reactive-react-redux';

There are some cases when we need to get an original object
instead of a tracked object.
Although it's not a recommended pattern,
the library exports a function as an escape hatch.
export type State = ...;

```javascript
const Component = () => {
const state = useTrackedState();
const dispatch = useUpdate();
const onClick = () => {
// this leaks a proxy outside render
dispatch({ type: 'FOO', value: state.foo });

// this works as expected
dispatch({ type: 'FOO', value: getUntrackedObject(state.foo) });
};
// ...
};
export type Action = ...;

const Context = createContext(new Proxy({}, {
get() { throw new Error('use Provider'); },
}) as PatchedStore<State, Action>);

export const Provider: React.FC<{ store: PatchedStore<State, Action> }> = ({
store,
children,
}) => createElement(Context.Provider, { value: store }, children);

export const useDispatch = () => useContext(Context).dispatch;

export const useSelector = <Selected>(
selector: (state: State) => Selected,
) => useSelectorOrig(useContext(Context), selector);

export const useTrackedState = () => useTrackedStateOrig(useContext(Context));
```
## Recipes

### useTrackedSelector

Expand Down Expand Up @@ -356,15 +367,15 @@ See [#32](https://github.com/dai-shi/reactive-react-redux/issues/32) for details

## Blogs

- [A deadly simple React bindings library for Redux with Hooks API](https://blog.axlight.com/posts/a-deadly-simple-react-bindings-library-for-redux-with-hooks-api/)
- [Developing React custom hooks for Redux without react-redux](https://blog.axlight.com/posts/developing-react-custom-hooks-for-redux-without-react-redux/)
- [Integrating React and Redux, with Hooks and Proxies](https://frontarm.com/daishi-kato/redux-custom-hooks/)
- [New React Redux coding style with hooks without selectors](https://blog.axlight.com/posts/new-react-redux-coding-style-with-hooks-without-selectors/)
- [Benchmark alpha-released hooks API in React Redux with alternatives](https://blog.axlight.com/posts/benchmark-alpha-released-hooks-api-in-react-redux-with-alternatives/)
- [Four patterns for global state with React hooks: Context or Redux](https://blog.axlight.com/posts/four-patterns-for-global-state-with-react-hooks-context-or-redux/)
- [Redux meets hooks for non-redux users: a small concrete example with reactive-react-redux](https://blog.axlight.com/posts/redux-meets-hooks-for-non-redux-users-a-small-concrete-example-with-reactive-react-redux/)
- [Redux-less context-based useSelector hook that has same performance as React-Redux](https://blog.axlight.com/posts/benchmark-react-tracked/)
- [What is state usage tracking? A novel approach to intuitive and performant global state with React hooks and Proxy](https://blog.axlight.com/posts/what-is-state-usage-tracking-a-novel-approach-to-intuitive-and-performant-api-with-react-hooks-and-proxy/)
- [Effortless render optimization with state usage tracking with React hooks](https://blog.axlight.com/posts/effortless-render-optimization-with-state-usage-tracking-with-react-hooks/)
- [How I developed a Concurrent Mode friendly library for React Redux](https://blog.axlight.com/posts/how-i-developed-a-concurrent-mode-friendly-library-for-react-redux/)
- [React hooks-oriented Redux coding pattern without thunks and action creators](https://blog.axlight.com/posts/react-hooks-oriented-redux-coding-pattern-without-thunks-and-action-creators/)
- [A deadly simple React bindings library for Redux with Hooks API](https://blog.axlight.com/posts/a-deadly-simple-react-bindings-library-for-redux-with-hooks-api/)
- [Developing React custom hooks for Redux without react-redux](https://blog.axlight.com/posts/developing-react-custom-hooks-for-redux-without-react-redux/)
- [Integrating React and Redux, with Hooks and Proxies](https://frontarm.com/daishi-kato/redux-custom-hooks/)
- [New React Redux coding style with hooks without selectors](https://blog.axlight.com/posts/new-react-redux-coding-style-with-hooks-without-selectors/)
- [Benchmark alpha-released hooks API in React Redux with alternatives](https://blog.axlight.com/posts/benchmark-alpha-released-hooks-api-in-react-redux-with-alternatives/)
- [Four patterns for global state with React hooks: Context or Redux](https://blog.axlight.com/posts/four-patterns-for-global-state-with-react-hooks-context-or-redux/)
- [Redux meets hooks for non-redux users: a small concrete example with reactive-react-redux](https://blog.axlight.com/posts/redux-meets-hooks-for-non-redux-users-a-small-concrete-example-with-reactive-react-redux/)
- [Redux-less context-based useSelector hook that has same performance as React-Redux](https://blog.axlight.com/posts/benchmark-react-tracked/)
- [What is state usage tracking? A novel approach to intuitive and performant global state with React hooks and Proxy](https://blog.axlight.com/posts/what-is-state-usage-tracking-a-novel-approach-to-intuitive-and-performant-api-with-react-hooks-and-proxy/)
- [Effortless render optimization with state usage tracking with React hooks](https://blog.axlight.com/posts/effortless-render-optimization-with-state-usage-tracking-with-react-hooks/)
- [How I developed a Concurrent Mode friendly library for React Redux](https://blog.axlight.com/posts/how-i-developed-a-concurrent-mode-friendly-library-for-react-redux/)
- [React hooks-oriented Redux coding pattern without thunks and action creators](https://blog.axlight.com/posts/react-hooks-oriented-redux-coding-pattern-without-thunks-and-action-creators/)
21 changes: 11 additions & 10 deletions __tests__/01_basic_spec.js → __tests__/01_basic_spec.tsx
Original file line number Diff line number Diff line change
@@ -1,36 +1,37 @@
import React, { StrictMode } from 'react';
import { createStore } from 'redux';
import { AnyAction, createStore } from 'redux';

import { render, fireEvent, cleanup } from '@testing-library/react';

import {
Provider,
patchStore,
useSelector,
useTrackedState,
useDispatch,
} from '../src/index';

describe('basic spec', () => {
afterEach(cleanup);

it('hooks are defiend', () => {
expect(useSelector).toBeDefined();
expect(useTrackedState).toBeDefined();
expect(useDispatch).toBeDefined();
});

it('create a component', () => {
const initialState = {
count1: 0,
};
const reducer = (state = initialState, action) => {
type State = typeof initialState;
const reducer = (state = initialState, action: AnyAction) => {
if (action.type === 'increment') {
return { ...state, count1: state.count1 + 1 };
}
return state;
};
const store = createStore(reducer);
const store = patchStore<State, AnyAction>(createStore(reducer));
const Counter = () => {
const value = useTrackedState();
const dispatch = useDispatch();
const value = useTrackedState(store);
const { dispatch } = store;
return (
<div>
<span>{value.count1}</span>
Expand All @@ -40,10 +41,10 @@ describe('basic spec', () => {
};
const App = () => (
<StrictMode>
<Provider store={store}>
<>
<Counter />
<Counter />
</Provider>
</>
</StrictMode>
);
const { getAllByText, container } = render(<App />);
Expand Down
Loading