Secure your code as it's written. Use Snyk Code to scan source code in minutes - no build needed - and fix issues immediately.
import React, { useTransition } from 'react';
import { createContext, useContextSelector } from 'use-context-selector';
import {
syncBlock,
useRegisterIncrementDispatcher,
initialState,
reducer,
ids,
useCheckTearing,
shallowEqual,
} from '../common';
const context = createContext(null);
const Provider = ({ children }) => {
const [state, dispatch] = React.useReducer(reducer, initialState);
return (
{children}
);
};
const Counter = React.memo(() => {
const count = useContextSelector(context, (v) => v[0].count);
syncBlock();
return <div>{count}</div>;
}, shallowEqual);
const initialState = {
count: 0,
text: 'hello',
};
const reducer = (state, action) => {
switch (action.type) {
case 'increment': return { ...state, count: state.count + 1 };
case 'decrement': return { ...state, count: state.count - 1 };
case 'setText': return { ...state, text: action.text };
default: throw new Error(`unknown action type: ${action.type}`);
}
};
const context = createContext(null);
const Counter = () => {
const count = useContextSelector(context, (v) => v[0].count);
const dispatch = useContextSelector(context, (v) => v[1]);
return (
<div>
{Math.random()}
<div>
<span>Count: {count}</span>
<button type="button"> dispatch({ type: 'increment' })}>+1</button>
<button type="button"> dispatch({ type: 'decrement' })}>-1</button>
</div>
</div>
);
};