Tag Archives: React Hooks

https://res.cloudinary.com/dpdbfabms/images/w_624,h_305/f_auto,q_auto/v1651573125/React-Context/React-Context.png?_i=AA

Effective use of Context in a React Application

The prerequisite to comprehend this article is a fair knowledge of Hooks. Hooks is a new addition in React 16.8 that let you use state and other React features without writing a class.

In a React application, we can pass data from parent component to child components using the prop. However, this is limited to certain type of properties such as Theme, locale preference, etc., which need to be used at global level in the application. With React Context, we can use the data or props without explicitly passing them as props to the component.

Context has three main elements. We need to understand these elements to utilize Context to the fullest.

  1. Context ObjectThe Context object is designed to share data globally in the application.
  2. Context ProviderThe Context object comes with a provider that can be used to consume Context data in the React component.
  3. Context Consumer The Context Consumer is wrapped inside the Context provider, and it is used to get access to the Context data.

In this article, let us see how to create a Theme Context using typescript step by step.

1.Create Theme Context Object. Export ThemeContext and set the Context default value to ‘undefined’.

Theme context object

2.Create the Theme object by using two Themes, for instance, here we are going to use ‘dark’ and ‘light’.

Create Theme Object

3.Create Theme Context provider.

Theme Context Provider

4.We created the Theme Context Provider by setting the Default Theme and function to change the Theme.

5.Subscribe Theme Context by wrapping the component with Context provider.

SubscribeThemeContext

6.Use or set the Context data as shown in the screenshot below.

Context data React

The concept of Context is simple yet effective. In this article, we covered how to use Context in the React Application with Theme Context example using TypeScript.

Should you have any queries, please contact MetaSys Software React experts, who have abundant experience in engineering applications using latest dev-tools such as React-Redux, React Hooks, React Router, React Bootstrap, etc.

You can reach out to us with any coding queries too! We would be happy to help!

Happy Coding!

https://res.cloudinary.com/dpdbfabms/images/w_624,h_344/f_auto,q_auto/v1651574438/react-hooks-1/react-hooks-1.png?_i=AA

Our experience of using React Hooks and what you can learn from it!

React JS is now a very popular programming language. React Hooks has unlocked new capabilities and allows you to create great applications. It allows one to write very compact code. We share our experience of how we have used React Hooks. We assume here that you have some React Programming knowledge.

React Hooks are functions that allow you to hook into React lifecycle and state features. They primarily serve as an alternative for classes. They can help in keeping your components clean and perform better. Hooks are a recent  addition in React version 16.8.0.

In this article, we are going to show you how to convert a React class into a functional component using the useState Hook.

Hooks don’t work inside classes because they let you use React without classes. We will use the built-in hooks instead of React lifecycle methods. Eg. useState, useEffect, useRef etc.

We are covering useState, useEffect, useRef React hooks in this article. useState() is used to replace the constructor functions and state declarations. While useEffect() is used to replace componentDidMount() and componentDidUpdate(). You can use useEffect as many times as you need to in single component. And the last one, useRef has another cool usage besides DOM refs, it is also a generic container whose current property is mutable, it also can hold any value similar to an instance property of a class.

Steps to convert a React class component into a functional component using React Hooks –

React Hooks

Step 1. Change ‘class ComponentName extends Component’ With ‘function ComponentName(props)‘

Step 2. Remove “this.” And “this.state” from the entire component.

Step 3. import React, { useState } from ‘react’

Step 4. Remove the constructor. Add its logic as shown above in the image for initializing the state variables with the help of useState hook.

Let’s understand conversion into useState, useEffect and useRef with examples –

  • useState() Hook –

The parameter of the useState hook is the initial value of the state. This hook provides the array with two values – the first is the name of the state and the second is the function name which updates the value of that state.

Eg.

const [num, setNum] = useState(0); //declaration

setNum(10) //use

Here num is the state name, setCount is the function that you can use anywhere in the component to update that state.

Here are some examples of setting or initializing state variables for different data types –

//Set an Integer

const [num, setNum] = useState(0);

setNum(10);

 

//Set a String

const [name, setUsername] = useState(‘John’);

setUsername(‘Smith’);

 

//Set a Boolean

const [isValid, setIsValid] = useState(false);

setIsValid(true);

 

//Set and Array

const [items, setItems] = useState([]);

setItems([0,1,2,3,4]);

setItems([{id:0, color:”red”},{id:1, color:”green”},{id:2, color:”blue”}]);

 

//Set and Object

const [form, setValues] = useState({

id: 0,

firstName: ‘’,

lastName: ‘’,

subscribe: false

})

 

setValues({

…form,

firstName: ‘Jamie’,

subscribe: true

})

 

 

  • Replace lifecycle methods (compentDidMount, componentWillUnmount,

 componentWillReceiveProps, componentDidUpdate) with useEffect

 

e.g.

const [items, setItems] = useState([]);

const [num, setNum] = useState(0);

 

  1. compentDidMount

 

useEffect(()=>{

setItems(items);

}, [])   // Here empty array indicates don’t look for any updates

 

b.componentWillUnmount

 

useEffect(()=>{

return () => {console.log(‘unmounting the component’)}

},[])

 

c. componentDidUpdate/componentWillReceiveProps

This will get executed when your ‘num’ state variable and ‘id’ props will get updated.

 

useEffect(()=>{

if (!isEmpty(num))

{

console.log(‘num changed = ’,num);

setItems(items);

}

 

if(!isEmpty(props.id))

{

console.log(‘props.id changed = ’,props.id);

}

},[num, props.id])

 

 

  • Use of useRef

 

const [num, setNum] = useState(0);

const prevNumRef = useRef();

useEffect(()=>{

prevNumRef.current = num;

})

const prevNum = prevNumRef.current;

return <h1>Current value : {num}, previous value = {prevNum}</h1>

 

Advantages

1.With React hooks, the component will be cleaner and easier to read (fewer lines of code). Hooks are easier to work with and to test.

2.It is easy to make code reusable. They don’t create another element in DOM like HOCs in React do.

3. useState – it allows to update different states with specific functions. The ability to move the state update logic as a separate hook.

 

Disadvantages

1.useEffect hook allows to merge three lifecycle methods such as componentDidMount, componentWillUnmount and componentDidUpdate into one and the issue with useEffect is the second parameters ,i.e. the array that we need to pass to define this behaviour. It is not explicit enough.

2.React Hooks are new additions to React. So to convert and test a complex class can be a time-consuming task initially .

3.Since it is relatively a new addition it may not be compatible with all third party libraries. But this is rapidly changing .

This is all about React Hooks in a nutshell. If you are looking to build any a mobile or web application using React technology, then please contact us.

Happy coding!