React Hooks - folio3
Amid the COVID-19 outbreak, Folio3 aims to help clinics serve patients with telemedicine effectively.

React Hooks

React Hooks
COMMENTS (0)
Tweet

React is a javascript framework for building interactive client side interfaces along with the integration with back-end server. React considers the UI as a set of reusable components. These components can either be a class component or a stateless functional component. Stateless components are used for making static UI components. Class components provide some nice features like state management and life cycle methods. Before React Hooks, state management and using life cycle function inside a functional component was not possible.

What Are Hooks?

Hooks launched in React 16.8 is a brand new feature that lets us use class component features like state, context and effects inside a stateless functional component. Hooks are basically functions that lets you use React features inside a functional component. For example, with the help of useState hook we can use state inside a functional component which was previously not possible. In this blog I will explain what the main differences are between functional and class components when we use state, context and effects.

useState Hook

Before React 16.8, functional components were used wherever stateless components were needed and class components where state was required. Now with the help of hooks we can use state inside a functional component. Let’s look at the following class component.
In a class component, we define the state as an object inside the constructor, then use it as this.state.[fieldname] throughout the class and update its value with the this.setState() function. Following is an example of how state is used inside a class component.

class Counter extends Component {
 constructor(props) {
   super(props);
   this.state = { 
     count: 0
   };
 }
  onIncrementClick = () => {
   this.setState(prevState => ({ count: prevState.count+1 }))
 }

 onResetClick = () => {
   this.setState({ count: 0 });
 }

 render() {
   const { count } = this.state;
   return (
     <div>
       <div>
         value of count: { count }
       </div>
       <div>
         <button onClick={ this.onIncrementClick }>Increment</button>
       </div>
       <div>
         <button onClick={ this.onResetClick }>Reset</button>
       </div>
     </div>
   );
 }
}

The following example shows how we can use React Hook useState to achieve what is done in the above example.

const Counter = (props) => {
 const [count, setCount] = useState(0);
 const onIncrementClick = () => {
   setCount(count+1);
 }
 const onResetClick = () => {
   setCount(0);
 }
 return (
   <div>
     <div>
       value of count: { count }
     </div>
     <div>
       <button onClick={ onIncrementClick }>Increment</button>
     </div>
     <div>
       <button onClick={ onResetClick }>Reset</button>
     </div>
   </div>
 );
}

In the above example, we used the useState hook. The useState hook returns an array with the first element representing the state and the second element representing a function. This function is used to set the value of this particular state variable. With ES6 we can use array destructuring syntax to easily get the state value and function in a single line like shown above. We can pass an initial value to the useState hook. In the example, I have passed 0 as the initial value for the count variable to the useState hook.

useContext Hook

This hook lets us use context in a much more convenient way. To understand how, let’s look at how context was previously used in the following class component.

const Content = React.createContext({ hello: 'world })

export default function App() {
 return (
   <Content.Consumer>
     { content =>
       content.hello === 'world &&
       "Hello World!"
     }
   </Content.Consumer>
 )
}

The above example consumes the context using a callback and it looks fine because we only have a  single callback in this case. Now consider a scenario in which we have more than one context.

const Context1 = React.createContext({ param: 'Hello' })
const Context2 = React.createContext({ param: 'World!' })

export default function App() {
 return (
   <Context1.Consumer>
     { context1 =>
       <Context2.Consumer>
         { context2 => `${context1.param} ${context2.param}!` }
       </CurrentUser.Consumer>
     }
   </CurrentRoute.Consumer>
 )
}

In the above case, to access the values of each context, we need to provide a callback. This will go on and on.
React Hooks to the rescue. With the help of the use context hook, we can avoid the use of callbacks. Lets see how.

const Context1 = React.createContext({ param: 'Hello' })
const Context2 = React.createContext({ param: 'World!' })

export default function App() {
 let context1 = useContext(Context1)
 let context2 = useContext(Context2)

 return (
   <div>
     `${context1.param} ${context2.param}!`
   </div>
 );
}

By using useContext hook we can easily access as many contexts as we want and avoid callbacks. This looks much more neat and readable.

useEffect Hook

The class components contain lifecycle methods which helps us to manipulate the component during the different periods of its life. Functional components don’t have them. With the help of the useEffect hook, we can get class component’s lifecycle methods like behaviour. We can use it like componentDidMount, componentDidUpdate, etc.

This hook takes a callback and that callback is called each time the component gets rendered. Now you might be thinking if it gets invoked on each render how can we use it as componentDidMount replacement. Well, it takes a second argument, an array. In that array, we can provide the props or state variables that when changed, the callback gets invoked.

If we only pass a callback to useEffect then it’s invoked each time the component is rendered.

useEffect(() => {
  console.log('Called upon each render');
});

In case we want it to behave like componentDidMount, we pass an empty array as second argument. Then the callback is invoked only once.

useEffect(() => {
  console.log('Component Did Mount');
}, []);

If we pass a state or prop variable in the array, then the callback is invoked only when that variable changes.

export default function App() {
 const [count, setCount] = useState(0);
 const onIncrementClick = () => {
   setCount(count+1);
 }

 useEffect(() => {
   console.log('Invoked when counter changes');
 }, [count]);


 return (
  <div>
    <button onClick={ onIncrementClick }>Increment</button>
  </div>
 );
}

The above callback will be invoked only when the count variable changes.

Conclusion

Hooks is a new feature that React has brought functional components on par with class components by providing hooks for state management, context, effects, etc inside functional components. Hooks will make components more readable and consistent because there is no need to use class components anymore. Hooks are backward compatible and can work alongside your existing components.

CALL

USA408 365 4638

VISIT

1301 Shoreway Road, Suite 160,

Belmont, CA 94002

Latest From Our Blog

Getting Started with Performance Testing Using ...

Getting Started with Performance Testing Using Apache Jmeter
May 10, 2022
  Performance testing plays an important role in application’s stability and scalability. We cannot make a product live without testing its pe...
Read more

Usability Testing on Mobile App

March 31, 2022
So let’s commence this discussion with a query. What do phone consumers spend most of their time on? On mobile apps? Yes, you read that correctly. ...
Read more

Integrated D365 and Magento 2.x in QA Life Cycle

March 30, 2022
  GOALS: The understanding of ERP and E-commerce integration as a QA Engineer. How to apply Requirement Elicitation techniques in this area of...
Read more