Skip to content
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

feat: usePrevious #154

Merged
merged 4 commits into from
Nov 18, 2019
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
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
3 changes: 3 additions & 0 deletions src/index.ts
Original file line number Diff line number Diff line change
Expand Up @@ -16,8 +16,10 @@ import usePagination from './usePagination';
import useBoolean from './useBoolean';
import useToggle from './useToggle';
import useSelections from './useSelections';
import usePrevious from './usePrevious';
import useMouse from './useMouse';


const useControlledValue: typeof useControllableValue = function (...args) {
console.warn(
'useControlledValue is deprecated and will be removed in the next major version. Please use useControllableValue instead.',
Expand Down Expand Up @@ -47,5 +49,6 @@ export {
useBoolean,
useToggle,
useSelections,
usePrevious,
useMouse,
};
78 changes: 78 additions & 0 deletions src/usePrevious/__tests__/index.test.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,78 @@
import { renderHook } from '@testing-library/react-hooks';
import usePrevious, { compareFunction as comFunc } from '..';

describe('usePrevious', () => {
it('should be defined', () => {
expect(usePrevious).toBeDefined();
});

function getHook<T>(initialValue?: T, compareFunction?: comFunc<T>) {
return renderHook(({ val, cmp }) => usePrevious<T>(val as T, cmp), {
initialProps: {
val: initialValue || 0,
cmp: compareFunction,
} as { val?: T; cmp?: comFunc<T> },
});
}

it('should return undefined on init', () => {
expect(getHook().result.current).toBeUndefined();
});

it('should update previous value only after render with different value', () => {
const hook = getHook(0, () => true);

expect(hook.result.current).toBeUndefined();
hook.rerender({ val: 1 });
expect(hook.result.current).toBe(0);

hook.rerender({ val: 2 });
expect(hook.result.current).toBe(1);

hook.rerender({ val: 3 });
expect(hook.result.current).toBe(2);

hook.rerender({ val: 4 });
expect(hook.result.current).toBe(3);

hook.rerender({ val: 5 });
expect(hook.result.current).toBe(4);
});

it('should work fine with `undefined` values', () => {
const hook = renderHook(({ value }) => usePrevious(value), {
initialProps: { value: undefined as undefined | number },
});

expect(hook.result.current).toBeUndefined();

hook.rerender({ value: 1 });
expect(hook.result.current).toBeUndefined();

hook.rerender({ value: undefined });
expect(hook.result.current).toBe(1);

hook.rerender({ value: 2 });
expect(hook.result.current).toBeUndefined();
});

it('should receive a predicate as a second parameter that will compare prev and current', () => {
const obj1 = { label: 'John', value: 'john' };
const obj2 = { label: 'Jonny', value: 'john' };
const obj3 = { label: 'Kate', value: 'kate' };
type Obj = { label: string; value: string };
const predicate = (a: Obj | undefined, b: Obj) => (a ? a.value !== b.value : true);

const hook = getHook(obj1 as Obj, predicate);

expect(hook.result.current).toBeUndefined();

hook.rerender({ val: obj2, cmp: predicate });

expect(hook.result.current).toBeUndefined();

hook.rerender({ val: obj3, cmp: predicate });

expect(hook.result.current).toBe(obj1);
});
});
18 changes: 18 additions & 0 deletions src/usePrevious/demo/demo1.jsx
Original file line number Diff line number Diff line change
@@ -0,0 +1,18 @@
import React, { useState } from 'react';
import { Button } from 'antd';
import usePrevious from '..';

export default () => {
const [count, setCount] = useState(0);
const previous = usePrevious(count);
return (
<>
<div>counter current value: {count}</div>
<div>counter previous value: {previous}</div>
<Button.Group>
<Button onClick={() => setCount(c => c + 1)}> increase </Button>
<Button onClick={() => setCount(c => c - 1)}> decrease </Button>
</Button.Group>
</>
);
};
18 changes: 18 additions & 0 deletions src/usePrevious/demo/demo1.tsx
Original file line number Diff line number Diff line change
@@ -0,0 +1,18 @@
import React, { useState } from 'react';
import { Button } from 'antd';
import usePrevious from '..';

export default () => {
const [count, setCount] = useState(0);
const previous = usePrevious(count);
return (
<>
<div>counter current value: {count}</div>
<div>counter previous value: {previous}</div>
<Button.Group>
<Button onClick={() => setCount(c => c + 1)}> increase </Button>
<Button onClick={() => setCount(c => c - 1)}> decrease </Button>
</Button.Group>
</>
);
};
98 changes: 98 additions & 0 deletions src/usePrevious/demo/demo2.jsx
Original file line number Diff line number Diff line change
@@ -0,0 +1,98 @@
import React, { useState } from 'react';
import { Button, Input } from 'antd';
import usePrevious from '..';

const nameCompareFunction = (prev, next) => {
if (!prev) {
return true;
}
if (prev.name !== next.name) {
return true;
}
return false;
};

const jobCompareFunction = (prev, next) => {
if (!prev) {
return true;
}
if (prev.job !== next.job) {
return true;
}
return false;
};

export default () => {
const [state, setState] = useState({
name: 'Jack',
job: 'student',
});
const [nameInput, setNameInput] = useState('');
const [jobInput, setJobInput] = useState('');
const previousName = usePrevious(state, nameCompareFunction);
const previousJob = usePrevious(state, jobCompareFunction);
return (
<>
<div
style={{
margin: 8,
border: '1px solid #e8e8e8',
padding: 8,
}}
>
current state:
<div>name: {state.name}</div>
<div>job: {state.job}</div>
</div>
<div>
{state.name}&#39;s previous name: {(previousName || {}).name}
</div>
<div
style={{
marginBottom: 16,
}}
>
{state.name}&#39;s previous job: {(previousJob || {}).job}
</div>
<Input.Group compact>
<Input
style={{
width: 220,
}}
value={nameInput}
onChange={e => setNameInput(e.target.value)}
placeholder={`${state.name}'s new name`}
/>
<Button
onClick={() => {
setState(s => ({ ...s, name: nameInput }));
}}
>
update
</Button>
</Input.Group>
<Input.Group
compact
style={{
marginTop: 16,
}}
>
<Input
style={{
width: 220,
}}
value={jobInput}
onChange={e => setJobInput(e.target.value)}
placeholder={`${state.name}'s new job`}
/>
<Button
onClick={() => {
setState(s => ({ ...s, job: jobInput }));
}}
>
update
</Button>
</Input.Group>
</>
);
};
82 changes: 82 additions & 0 deletions src/usePrevious/demo/demo2.tsx
Original file line number Diff line number Diff line change
@@ -0,0 +1,82 @@
import React, { useState } from 'react';
import { Button, Input } from 'antd';
import usePrevious from '..';

interface Person {
name: string;
job: string;
}

const nameCompareFunction = (prev: Person | undefined, next: Person) => {
if (!prev) {
return true;
}
if (prev.name !== next.name) {
return true;
}
return false;
};

const jobCompareFunction = (prev: Person | undefined, next: Person) => {
if (!prev) {
return true;
}
if (prev.job !== next.job) {
return true;
}
return false;
};

export default () => {
const [state, setState] = useState({ name: 'Jack', job: 'student' });
const [nameInput, setNameInput] = useState('');
const [jobInput, setJobInput] = useState('');
const previousName = usePrevious(state, nameCompareFunction);
const previousJob = usePrevious(state, jobCompareFunction);

return (
<>
<div style={{ margin: 8, border: '1px solid #e8e8e8', padding: 8 }}>
current state:
<div>name: {state.name}</div>
<div>job: {state.job}</div>
</div>
<div>
{state.name}&#39;s previous name: {(previousName || {}).name}
</div>
<div style={{ marginBottom: 16 }}>
{state.name}&#39;s previous job: {(previousJob || {}).job}
</div>
<Input.Group compact>
<Input
style={{ width: 220 }}
value={nameInput}
onChange={e => setNameInput(e.target.value)}
placeholder={`${state.name}'s new name`}
/>
<Button
onClick={() => {
setState(s => ({ ...s, name: nameInput }));
}}
>
update
</Button>
</Input.Group>
<Input.Group compact style={{ marginTop: 16 }}>
<Input
style={{ width: 220 }}
value={jobInput}
onChange={e => setJobInput(e.target.value)}
placeholder={`${state.name}'s new job`}
/>
<Button
onClick={() => {
setState(s => ({ ...s, job: jobInput }));
}}
>
update
</Button>
</Input.Group>
</>
);
};
16 changes: 16 additions & 0 deletions src/usePrevious/index.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,16 @@
import React, { useRef } from 'react';

export type compareFunction<T> = (prev: T | undefined, next: T) => boolean;

export default <T>(state: T, compare?: compareFunction<T>): T | undefined => {
const prevRef = useRef<T>();
const curRef = useRef<T>();

const needUpdate = typeof compare === 'function' ? compare(curRef.current, state) : true;
if (needUpdate) {
prevRef.current = curRef.current;
curRef.current = state;
}

return prevRef.current;
};
58 changes: 58 additions & 0 deletions src/usePrevious/index_cn.mdx
Original file line number Diff line number Diff line change
@@ -0,0 +1,58 @@
---
name: usePrevious
route: /usePrevious
menu: 'State'
edit: false
sidebar: true
---

import JackBox from 'jackbox';

import Demo1 from './demo/demo1';
import Demo1CodeTsx from '!raw-loader!./demo/demo1.tsx';
import Demo1CodeJsx from '!raw-loader!./demo/demo1.jsx';

import Demo2 from './demo/demo2';
import Demo2CodeJsx from '!raw-loader!./demo/demo2.jsx';
import Demo2CodeTsx from '!raw-loader!./demo/demo2.tsx';


# usePrevious

保存上一次渲染时状态的 Hook


## 代码演示

### 基本用法

<JackBox jsCode={Demo1CodeJsx} tsCode={Demo1CodeTsx} demoName='基本用法' description='记录上次的 count 值'>
<Demo1 />
</JackBox>

### 使用 compare function

<JackBox jsCode={Demo2CodeJsx} tsCode={Demo2CodeTsx} demoName='使用 compare function' description='只有 compare function 返回 true 时,才会记录值的变化'>
<Demo2 />
</JackBox>

## API
```
const previousState: T = usePrevious<T>(
state: T,
compareFunction: (prev: T | undefined, next: T) => boolean
);
```

### Result

| 参数 | 说明 | 类型 |
|------|----------|------|
| previousState | 上次 state 的值 | T |

### Params

| 参数 | 说明 | 类型 | 默认值 |
|---------|----------|------------------------|--------|
| state | 需要记录变化的值 | T | - |
| compareFunction | 可选,自定义值变化的规则 | (prev: T \| undefined, next: T) => boolean | - |
Loading