Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- import React, { useState } from 'react';
- import { createStore } from 'redux';
- const store = createStore(reducer);
- function useCount() {
- const [count, setCount] = useState(store.getState().count);
- store.subscribe(() => {
- setCount(store.getState().count);
- });
- return count;
- };
- function useSetCount() {
- return store.dispatch;
- };
- const initialState = {
- count: 0
- };
- function reducer(state = initialState, action) {
- switch (action.type) {
- case 'increment':
- return {
- count: state.count + 1
- };
- case 'decrement':
- return {
- count: state.count - 1
- };
- case 'reset':
- return {
- count: 0
- };
- default:
- return state;
- };
- };
- const App = () => (
- <>
- <CountDisplay />
- <div>
- <IncreaseCountButton />
- <DecreaseCountButton />
- <ResetCountButton />
- </div>
- </>
- );
- function CountDisplay() {
- const count = useCount();
- return (
- <>
- <h1>The current count state:</h1>
- <p>{count}</p>
- </>
- );
- };
- function UpdateCountButton({children, onClick}) {
- return <button onClick={onClick}>{children}</button>;
- };
- function IncreaseCountButton() {
- const setCount = useSetCount();
- function increment() {
- setCount({ type: 'increment' });
- };
- return <UpdateCountButton onClick={increment}>+</UpdateCountButton>;
- };
- function DecreaseCountButton() {
- const setCount = useSetCount();
- function decrement() {
- setCount({ type: 'decrement' });
- };
- return <UpdateCountButton onClick={decrement}>-</UpdateCountButton>;
- };
- function ResetCountButton() {
- const setCount = useSetCount();
- function reset() {
- setCount({ type: 'reset' });
- };
- return <UpdateCountButton onClick={reset}>reset</UpdateCountButton>;
- };
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement