React Base Fiddle (JSX)
Starting point for creating JSFiddles with React.
by Dan
HTML
<script src="https://unpkg.com/react@16/umd/react.development.js"></script>
<script src="https://unpkg.com/react-dom@16/umd/react-dom.development.js"></script>
<div id="app">
<!-- This element's contents will be replaced with your component. -->
</div>
Babel + JSX
// State 1/3 async state ----------
// ---------------------------------------------------
const Counter = () => {
const [a, setA] = React.useState(0);
const [b, setB] = React.useState(0);
const incrementAsync = () => {
setTimeout(() => {
setA(a + 1);
setB(b + 1);
}, 1000);
};
console.log('re-render'); // Fires twice per click
return (
<div>
A: {a}, B: {b}
<button onClick={incrementAsync}>Increment</button>
</div>
);
};
// State 2/3 combined state ----------
// ---------------------------------------------------
const CounterCombinedState = () => {
const [state, setState] = React.useState({a: 0, b: 0});
const incrementAsync = () => {
setTimeout(() => {
setState({a: state.a + 1, b: state.b + 1});
}, 1000);
};
console.log('re-render'); // Fires once per click
return (
<div>
A: {state.a}, B: {state.b}
<button onClick={incrementAsync}>Increment</button>
</div>
);
};
// State 3/3 useReducer ----------
// ---------------------------------------------------
const initialState = { a: 0, b: 0 };
function reducer(state, action) {
switch (action.type) {
case 'increment':
return { a: state.a + 1, b: state.b + 1};
default:
throw new Error();
}
}
const CounterReducer = () => {
const [state, dispatch] = useReducer(reducer, initialState);
const incrementAsync = () => {
setTimeout(() => {
dispatch({type: 'increment'})
}, 1000);
};
console.log('re-render'); // Fires once per click
return (
<div>
A: {state.a}, B: {state.b}
<button onClick={incrementAsync}>Increment</button>
</div>
);
};
// Memorization 1/5 ----------
// ---------------------------------------------------
const CounterApp = () => {
const [value, setValue] = React.useState(""); // setValue causes re-render of
// unmemorized components
return (
<div>
<input type="text" onChange={(e) =>...