Functional Component using hooks in react and redux JavaScript libraries.

AHMED M A
3 min readMar 21, 2021

Many years ago functional component has limited functionality until new version of react React v16.8.0 been developed with new features, one of these features called react hooks, so instead of using the class component in react and redux, we can use a functional component by using hooks. We are going to explain them in the example, we will make a table to compare the using of the functional component with hooks and using class component without hooks, first will compare the state between both components:

As you see above, when we use functional components, we used fewer codes and nice format codes, also in the functional component we didn’t need to use any previous state to access the previous state.

Second, compare we are using life cycle methods in react when we use

We used useEffect hooks instead of componentDidMount life cycle methods in the functional components.

Another use of hooks in the functional component is to connect to redux and map state coming from redux to props of react component, so we are going to use useSelecetor :

As you see above functional compnent used less coding and nice format, also we don’t have to use connect(stateToProps, Book) method, because useSelector does that for us. Also, you can use another hook called useContext, this hook has access to state and dispatch in redux.

Now we are going to map our dispatch function to our props in react

In functional component useDispatch() hook easier to define and call.

Another use of the hook is a ref, which Is the ability to access the HTML DOM or react elements. let’s take an example in the form :

So when we ref we don’t have to use handleChange and e.target , ref can access to DOM nodes or react elements.

The last hook we can use in react is useContext() it’s most powerful hook, you can use it as a global accessor, your data can be accessed in many different components

By using context we passed the state to Comments component, also in the middle component CommentsContainer we didn’t have to pass state down explicitly.

--

--