This post covers programming data requests via fetch, axios, JavaScript promises etc. using Redux. Redux can now be configured with hooks; allowing you to remove connect from components.
There are two main types of hooks that are utilised in React; useState
and useEffect
.
This hooks enables you to be able to setState
locally within a component. Here is an example of how useState might be utilised in a component.
const Example = (props) => {
const [count, setCount] = React.useState(0);
return (
<button onClick={() => setCount(count+1)}>
{count}
</button>)
}
Like componentDidMount()
, this hook will be called once your component has rendered.
useEffect(() => {
dispatch(exampleAction())
}, [dispatch])
The hook allows you to use the state within your application. It is similar to mapStateToProps
.
const state = useSelector(state => state.data)
This hook behaves in a similar way to mapDispatchToProps
.
const dispatch = useDispatch()
useEffect(() => {
dispatch(exampleAction())
}, [dispatch])