Skip to content

Add useState example #128

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 6 commits into from
Jan 26, 2019
Merged
Show file tree
Hide file tree
Changes from 4 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
27 changes: 27 additions & 0 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -770,6 +770,33 @@ export default () => (

> https://reactjs.org/docs/hooks-intro.html

#### - useState

> https://reactjs.org/docs/hooks-reference.html#usestate

```tsx
import * as React from 'react';

interface CounterProps {
Copy link
Owner

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Let's use type Props from now on for new components, I'll be refactoring all existing one to that too

initialCount: number;
}

export default function Counter({initialCount}: CounterProps) {
const [count, setCount] = React.useState(initialCount);
return (
<>
Count: {count}
<button onClick={() => setCount(initialCount)}>Reset</button>
<button onClick={() => setCount(prevCount => prevCount + 1)}>+</button>
<button onClick={() => setCount(prevCount => prevCount - 1)}>-</button>
</>
);
}

```

[⇧ back to top](#table-of-contents)

#### - useReducer
Hook for state management like Redux in a function component.

Expand Down
8 changes: 8 additions & 0 deletions README_SOURCE.md
Original file line number Diff line number Diff line change
Expand Up @@ -313,6 +313,14 @@ const mapDispatchToProps = (dispatch: Dispatch<ActionType>) => ({

> https://reactjs.org/docs/hooks-intro.html

#### - useState

> https://reactjs.org/docs/hooks-reference.html#usestate

::codeblock='playground/src/hooks/use-state.tsx'::

[⇧ back to top](#table-of-contents)

#### - useReducer
Hook for state management like Redux in a function component.

Expand Down
17 changes: 17 additions & 0 deletions playground/src/hooks/use-state.tsx
Original file line number Diff line number Diff line change
@@ -0,0 +1,17 @@
import * as React from 'react';

interface CounterProps {
initialCount: number;
}

export default function Counter({initialCount}: CounterProps) {
const [count, setCount] = React.useState(initialCount);
return (
<>
Count: {count}
<button onClick={() => setCount(initialCount)}>Reset</button>
<button onClick={() => setCount(prevCount => prevCount + 1)}>+</button>
<button onClick={() => setCount(prevCount => prevCount - 1)}>-</button>
</>
);
}