Martin Lechner
27.06.2019
Martin Lechner
Fullstack Engineer at Autoscout24
I β€οΈ π¨βπ©βπ§βπ¦, Functional Programming, Photography, Bouldering & Boardgames
Nope π’
Code re-use for handling translations
function Example() {
return (
<Translation>
{
(translate) => <p>{translate('my-translation-key')}</p>
}
</Translation>
);
}
function MyComponent({ translate }) {
return <p>{translate('my-translation-key')}</p>
}
export default withTranslation()(MyComponent);
function MyComponent() {
const { translate } = useTranslation();
return <p>{translate('my-translation-key')}</p>
}
class Example extends React.Component {
constructor(props) {
super(props);
this.state = {
count: 0
};
}
render() {
return (
<div>
<p>You clicked {this.state.count} times</p>
<button onClick={() => this.setState({ count: this.state.count + 1 })}>
Click me
</button>
</div>
);
}
}
import React, { useState } from 'react';
function Counter() {
const [count, setCount] = useState(0);
return (
<div>
<p>You clicked {count} times.</p>
<button onClick={() => setCount(count + 1)}>
Inc
</button>
</div>
)
}
const [count, setCount] = useState(0);
<button onClick={() => setCount(c => c + 1)}>
Inc
</button>
eslint-plugin-react-hooks
ts-lint-react-hooks
function Counter() {
const [count, setCount] = useState(0);
useEffect(() => {
document.title = `You clicked ${count} times`;
});
return (
<div>
<p>You clicked {count} times</p>
<button onClick={()=> setCount(count + 1)}>
Click me
</button>
</div>
);
}
Click button
useEffect(() => {
websocket.connect(props.customerId);
});
useEffect(() => {
websocket.connect(props.customerId);
return () => websocket.disconnect(props.customerId);
});
useEffect(() => {
websocket.connect(props.customerId);
return () => websocket.disconnect(props.customerId);
}, [props.customerId]);
useEffect(() => {
...
}, []);
const [count, setCount] = useState(0);
useEffect(() => {
const id = setInterval(() => {
setCount(count + 1);
}, 1000);
return () => clearInterval(id);
}, [count]);
const [count, setCount] = useState(0);
useEffect(() => {
const id = setInterval(() => {
setCount(c => c + 1);
}, 1000);
return () => clearInterval(id);
}, []);
function useApi(url) {
const [error, setError] = useState(null);
const [loading, setLoading] = useState(false);
const [data, setData] = useState(null)
useEffect(() => ???)
return { error, loading, data };
}
function useApi(url) {
const [error, setError] = useState(null);
const [loading, setLoading] = useState(false);
const [data, setData] = useState(null)
useEffect(() => {
const fetchData = async () => {
setLoading(true);
setError(null);
???
setLoading(false);
};
fetchData();
}, [url]);
return { error, loading, data };
}
function useApi(url) {
const [error, setError] = useState(null);
const [loading, setLoading] = useState(false);
const [data, setData] = useState(null)
useEffect(() => {
const fetchData = async () => {
setLoading(true);
setError(null);
try {
const response = await axios.get(url);
setData(response.data);
} catch (e) {
setError(e);
}
setLoading(false);
};
fetchData();
}, [url]);
return { error, loading, data };
}
import axios from 'axios';
import { renderHook } from '@testing-library/react-hooks';
import { useApi } from './useApi';
jest.mock('axios');
it('should fetch data', async () => {
axios.get.mockResolvedValue({ data: '1' });
const { result, waitForNextUpdate } = renderHook(() => useApi('test'));
expect(result.current.loading).toEqual(true);
await waitForNextUpdate();
expect(result.current.loading).toEqual(false);
expect(result.current.data).toEqual('1');
});
const value = useContext(MyContext);
const refContainer = useRef(initialValue);
refContainer.current = 123;
refContainer.current
// 123
function TextInputWithFocusButton() {
const inputEl = useRef(null);
const onButtonClick = () => {
inputEl.current.focus();
};
return (
<>
<input ref={inputEl} type="text" />
<button onClick={onButtonClick}>Focus input</button>
</>
);
}
const memoizedCallback = useCallback(
() => {
doSomething(a, b);
},
[a, b],
);
function MeasureExample() {
const [height, setHeight] = useState(0);
const measuredRef = useCallback(node => {
if (node !== null) {
setHeight(node.getBoundingClientRect().height);
}
}, []);
return (
<>
<h1 ref={measuredRef}>Hello, world</h1>
<h2>The above header is {Math.round(height)}px tall</h2>
</>
);
}
const [state, dispatch] = useReducer(reducer, initialArg, init);
const initialState = {count: 0};
function reducer(state, action) {
switch (action.type) {
case 'increment':
return {count: state.count + 1};
case 'decrement':
return {count: state.count - 1};
default:
throw new Error();
}
}
function Counter() {
const [state, dispatch] = useReducer(reducer, initialState);
return (
<>
Count: {state.count}
<button onClick={() => dispatch({type: 'increment'})}>
+</button>
<button onClick={() => dispatch({type: 'decrement'})}>
-</button>
</>);
}
const memoizedValue = useMemo(() => computeExpensiveValue(a, b), [a, b]);