React — Hooking it on!

WalkingTree Technologies
4 min readFeb 25, 2019

--

By Abhilasha Sinha React February 25, 2019

React Hooks are the latest additions to the React block (React version 16.8) as they bring along great capabilities to revolutionize and energize, the feeble and simple looking Functional components.

As we know, React supports two types of components, namely, Functional and Class. The important difference between them is that we cannot handle the state or any life cycle methods in Functional components.

Hooks provide a way of adding these capabilities and many others to REACT’s Functional components.

In this blog, we will find some good ways and good reasons to put React hooks to use.

Visit our REACT Technology Page to know how WalkingTree Technologies helps unlock the true potential of REACT.

Contact us today for more information on our application development services in REACT.

Reusing Stateful Logic and Avoiding Duplication

In the class components, whenever we need the logic relating to a manipulating state, or we need to fetch data from API, etc. , we usually make use of lifecycle events while the logic will be specific to the class component.

Let us consider an example of fetching user data and presenting the same on the UI.

We will handle the user data in our application state.

In a class component we will do the following:

  1. Initialize the state to an empty array in the constructor
  2. Make the API call using axios in componentDidMount() to fetch the data
  3. If there is any update in the search filter, the API call will be handled again in the componentDidUpdate() lifecycle event handler

class UsersClass extends Component { state = { users: [] }; componentDidMount() { console.log(“componentDidMount called”); axios.get(‘https://hooks-demo-a6d15.firebaseio.com/users.json') .then(res => { const users=[]; for (const key in res.data){ users.push({ id: key, name :res.data[key].name, age: res.data[key].age, interests: res.data[key].interests}); } this.setState({ users } ); }) .catch(err => { console.log(err); }); } render () { const users = this.state.users.map((user)=>{ return <User name={user.name} age={user.age} interests={user.interests} key={user.id} /> }) return ( <div> {users} </div> ); } } export default UsersClass;

class UsersClass extends Component {

console.log(“componentDidMount called”);

axios.get(‘https://hooks-demo-a6d15.firebaseio.com/users.json')

for (const key in res.data){

name :res.data[key].name,

interests: res.data[key].interests});

this.setState({ users } );

const users = this.state.users.map((user)=>{

interests={user.interests}

export default UsersClass;

The class component UsersClass will look like the one demonstrated above and will utilize a presentation component called User to display individual user details in a card.

Also, if the user searches for a specific name, the API call will have to be initiated again for the specific user name in the componentDidUpdate() function.

All of the above logic will be specific to our UsersClass component and we cannot reuse any of it, if we have a similar situation (making an API call and/or updating state) in another component.

This is the biggest differentiator that hooks provide in Functional components.

The standard useState and useEffect hooks enable the incorporation of state and life cycle event hooks in Functional components.

The useState hook

The useState hook lets us add the React state to functional components. This function hook takes the initial value of state as an argument and returns a two-element array containing the state value, and a function to update that value.

const [users, setUsers] = useState([]);

const [users, setUsers] = useState([]);

useState takes the initial value as the input and returns the current state and the function to update the state(like the setState in the class components).
Now, we can get the current state using the first value returned (users) and use the second value returned (setUsers) if we need to update the state.

All of this can be achieved without the keyword ‘this’ being attached to it, as this pertains to a function and not a class.

The useEffect Hook

In the class components, we put any side-effects like API requests, manual DOM mutations, and logging into the lifecycle methods componentDidMount and componentDidUpdate. The useEffect hook handles the effects in the same way for functional components as well. This hook contains the logic to be executed after render.
The useEffect takes one mandatory parameter which is, the function that gets executed after render. By default, it gets executed every time render gets executed.

This can be optimized by making use of the second optional parameter.
If passed as an [](empty array), it gets executed only once, and if passed as some value [users], it gets executed only when the value, being passed as the second parameter changes.

For the user fetch example, only to get the user data in useEffect as below.

const Users = props =>{ const [users, setUsers] = useState([]); useEffect(() => { console.log(“useEffect called”); axios.get(‘https://hooks-demo-a6d15.firebaseio.com/users.json') .then(res => { const users=[] for (const key in res.data){ users.push({ id: key, name :res.data[key].name, age: res.data[key].age, interests: res.data[key].interests}); } setUsers( users ); }) .catch(err => { console.log(err); }); },[]);

const [users, setUsers] = useState([]);

console.log(“useEffect called”);

axios.get(‘https://hooks-demo-a6d15.firebaseio.com/users.json')

for (const key in res.data){

name :res.data[key].name,

interests: res.data[key].interests});

This is the optimal approach if we want to fetch the data again while the search criteria or the dependent data changes.

How can Hooks be reused?

You may also be interested in other blogs on REACT from our Experts at WalkingTree Technologies.

Follow us on :
https://www.facebook.com/walkingtreetech/
https://www.linkedin.com/company/walking-tree-Technologies
https://twitter.com/walkingtreetech
https://www.youtube.com/channel/UCH5y9upqT2M7uWwgRWjCWBg

Originally published at walkingtree.tech on February 25, 2019.

--

--

WalkingTree Technologies
WalkingTree Technologies

Written by WalkingTree Technologies

WalkingTree is an IT software and service provider recognized for its passion for technology.

No responses yet