React Hooks

React Hooks

In React, functional components used to be stateless components, which means they don't use state, props and React life cycle methods. Class components in the other hand were the preferred approach since it is state-full and gave users more flexibility and capability. Class components use more intricate code structures and more boilerplate codes while functional components use much less which gave functional components a higher readability and efficiency.

Boilerplate codes are the standardized code snippets developers has to use whenever developing a component. As an example when someone starts to develop a class component there are some common functions, methods, etc. they have to use in order to develop the component perfectly. These common lines of code are known as boilerplate code. In React, there is significantly fewer boilerplate codes in functional components compared to class components.

Even though the use of functional components made the application much more performance-optimized, the issue was that functional components were limited in contrast to class components. As a in contrast to class components, React introduced hooks in its version 16.8.

Hooks can be used in functional components as well as in class components. Although hooks gave a significant enhancement to functional components making them now able to use state, props and React life cycle methods. Thus the limitation functional components had was fixed and they became the recommended component to use in React since version 16.8

In React, hooks are standard JavaScript functions provided in React library. Each hook/function returns a different element/value according to he manner in which those functions are utilized.

As an example, the useState() hook is developed to let functional components use state variables. As previously mentioned, the usage of state variables was not possible for functional components before the release of React 16.8. The useState() hook helps functional components to use state and constitutes a standard JavaScript function that returns an array of two elements. The 0th index of this array is a variable which the developer can use as a state variable. 1st index is the function to update this variable. In contrast, this is like how the class components use this.state.variable_name and this.setState({variable_name}). The syntax of useState() hook is as below.

const [variable, setVariable] = useState(“initialValue”);

In here variable is the name of the state variable. The developer may utilize this like a state variable in class components. And setVariable is the function that developer should use in order to update variable. Finally the initialValue is the initial value of the variable.

The useState hook is JavaScript function which returns an array with these two elements. With the array de-structuring feature of JavaScript developers can assign any name to these returned elements and use them in their component.

In the above line of code, since there is an initial value assigned to variable, when that variable is used anywhere in the code, at first, it will display “initialValue”.

Using

setVariable(“anotherValue”)

To update the state will assign the value of variable to “anotherValue”. The useState() hook is extremely important and valuable in functional components. It can be specially used in certain scenarios such as

1.??????Handling user inputs

2.??????Updating a counter

3.??????Managing the visibility of element

Another important situation in React is managing the side effects. The useEffect() hook is developed to serve this purpose. The useEffect() can be used to control the side effects specifically external to the component scope.

This is similar to the use of React life cycle methods in class components such as componentDidMount method. The useEffect() hook can be used instead of componentDidMount method in a functional component.

The syntax of this hook is

useEffect(()=>{ yourCode },[dependencies]);

In here, yourCode is the lines of code or the function call that need to be done inside a lifecycle method. This can be customized and the useEffect() hook will run this part on the initial render and on each time the page mounts.

Additionally, by using dependencies the user can control when the useEffect() hook will be called. The useEffect() will run on every mount and whenever the value of the dependencies change. Although this dependencies array is optional, developers can pass this as an empty array and the hook will only be called once. Otherwise, if necessary the user can assign a state or a prop on which the effects can depend.

The most popular method to pass data from parent to child in react is using props. But a significant issue with props is that they can cause prop drilling. Prop drilling is when a prop must to be passed down all the way to a deeper level in parent-child hierarchy. In this scenario, all the child components in between will need to read and manipulate the props even if they don’t need it. This can have an effect on the performance of the application, as well as the quality, readability and the maintainability of the code itself.

The useContext() is a great hook which can be used to send data directly to a particular component preventing the in between components to have undesirable access. This way the prop drilling can be avoided and overall performance will not be negatively affected.

To use this hook, it is important to define a context first using:

const MyContext = React.createContext(defaultValue)

In here MyContext is defined using React’s createContext method and the defaultValue ?is the value MyContext will use if there are no Providers.

This MyContext will be used as a wrapper element for the child component to pass data.

<MyContext.Provider value={data}>

?<ChildComponent />

</MyContext.Provider>

Above is how to render a child component with the use of useContext() hook. It is important to note that a Provider method should be called like <MyContext.Provider and then the data have to be passed as a value prop. Although, in here passing multiple props is not possible and will have to send an object as the data being transferred. This value prop is customizable but it is advisable, to use the default name “value” since it’s easier to read and maintain the code that way.

Once the parent component have rendered a child component like this, child component can then use

const data = useContext(MyContext);

to assign the passed data to a variable.

The useRef() hook is an essential tool in functional programming for directly manipulating the DOM without triggering a re-render, while still changing the component's state. Its most common use is to store a mutable value that should not be changed upon re-renders, such as a counter that needs to maintain its value regardless of how many times the page is rendered. In addition to storing values, useRef() also enables the direct manipulation of DOM elements.

To use this hook, declare a constant using the syntax:

const myRef = useRef(initialValue);

The constant myRef is used to assign the useRef, which takes an initialValue as a parameter. For example, myRef can be used as a counter and assigned the value of 0.

And Calling the line of code

myRef += 1;

will add one to the value

The useState() hook is a useful tool, but it may not be sufficient for handling complex states. In such cases, the useReducer() hook becomes essential. This hook functions similarly to useState() in that it can manipulate state, but it also provides the added benefit of being able to manage more complex state updates.

To use the useReducer() hook, a dispatch function is utilized, which can be somewhat complex to implement. The syntax for this hook is as follows:

const [state, dispatch] = useReducer(reducer, initialState);

Here, the array de-structuring method is utilized, and the state variable can be used in an element. The dispatch method is similar to the setState() method in useState() and is used to call the useReducer() hook. When it is called, the reducer function is triggered. This function must be developed in the component based on the logic required for use with useReducer(). Finally, the initialState parameter sets the initial value of the state.

In conclusion, React hooks are a powerful and essential feature for developing scalable and efficient React applications. They provide a more elegant and concise way to manage state and logic, making it easier to build and maintain complex components.

The useState() hook allows for simple state management, while the useEffect() hook enables the use of side effects. The useContext() hook provides a way to share data between components, while useRef() allows for the direct manipulation of the DOM. Finally, the useReducer() hook provides a way to handle complex state management, especially in cases where useState() falls short.

By mastering these hooks, developers can greatly improve their React skills and create applications that are easier to read, test, and maintain.

#React #ReactHooks #FunctionalComponents #ClassComponents #State #Props #BoilerplateCode #PerformanceOptimization #UseState #UseEffect #UseContext #PropDrilling #PerformanceImprovement #Readability #Maintainability #JavaScript #WebDevelopment

要查看或添加评论,请登录

Nad Mahawithana的更多文章

  • Mitigating System Failures through Predictive Analytics

    Mitigating System Failures through Predictive Analytics

    Systems and how they malfunction A system refers here is related to a application if not a software program and other…

  • History of Artificial Intelligence

    History of Artificial Intelligence

    Artificial Intelligence is simply mimicking the human behavior through a series of computer systems. Notwithstanding…

  • Rendering in React

    Rendering in React

    Rendering is the process of converting the code in to a visual representation which people can interact with. This is…

社区洞察

其他会员也浏览了