umma.dev

Data Requests with Hooks and Redux

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.

Hooks in ReactJS

There are two main types of hooks that are utilised in React; useState and useEffect.

useState

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>)
}

useEffect

Like componentDidMount(), this hook will be called once your component has rendered.

useEffect(() => {
		dispatch(exampleAction())
	}, [dispatch])

React-Redux Hooks

There are a number of hooks provided by Redux which enable to you to take to deal with different parts of Redux, from the store to the reducer to dispatching. Below are two hooks which help to make data requests.

useSelector

The hook allows you to use the state within your application. It is similar to mapStateToProps.

const state = useSelector(state => state.data)

useDispatch

This hook behaves in a similar way to mapDispatchToProps.

const dispatch = useDispatch()

useEffect(() => {
		dispatch(exampleAction())
	}, [dispatch])