James Ellis

James Ellis

1567843583

Implementing React Life Cycles Using Reason React Hooks

After the release of Reason React Hooks, most of the developers have upgraded code base to support the hooks. Reason react community has also provided the script for upgradation but it just wraps the existing component using *ReasonReactCompact.wrapReasonReactForReact*to hooks components. *It doesn’t add the logic for hooks as it depends on the use-case and there is no direct mapping between both the components.

As I was upgrading the repository, I found some difficulties in upgrading the lifecycles to support the hooks. Therefore I have listed a small cheat sheet as a point of reference for conversion of those lifecycles. Before diving into the implementation using hooks a brief intro on React lifecycles and React Hooks.

React Hooks

Before hooks, for sharing state logic between the components we have to depend upon some of the patterns like HOCs(Higher Order Components) or render props (function as a child). But these lead to a code which is difficult to understand as it will be wrapped with lots of other components.

With hooks, you can create a custom component and can share the logic with the help of that component. As mentioned here

Hooks allow you to reuse stateful logic without changing your component hierarchy. This makes it easy to share Hooks among many components or with the community.

Using hooks, you can break all the lifecycles, which are used in React classes, into a separate component and test them and re-use them without creating a giant complex class with all the lifecycles in it. From the react site

Hooks let you split one component into smaller functions based on what pieces are related (such as setting up a subscription or fetching data), rather than forcing a split based on lifecycle methods

So basically hooks are a way to create a **stateful function **with the ability to reuse and break the components to create a better abstraction of the components.

React Lifecycles

For every react component, there is a cycle attached to it from the creation of react component to its deletion inside the DOM. During this cycle, several methods are called according to the various stages of the component. This cycle is called React Lifecycle. React Component lifecycle is divided into 4 stages:-

  • Initialization
  • Mounting
  • Updating
  • Unmounting

For visual reference that how life cycles work in react, check out this

Lifecycle methods called while initializing the component

In this stage, mostly the initial properties of the component are set. You can define the state, set default props and much more. Below are the methods that are called in this stage.

.constructor — This life cycle method is called before render and is used for initializing the state or to create some of the bindings for the event listener that the component will use.

type state = { counter: int };
	

	// Assign intial state in constructor method
	let initialState = () => { counter: 0 };
	

	[@react.component]
	let make = () => {
	  let (state, setState) => React.useState(initialState);
	  
	  "initial state is set using hooks" -> React.string;
	};

constructor.re

Lifecycle methods called while mounting the component

Below are the lifecycle methods which are called when the component is created or inserted inside the DOM.

render — This lifecycle method is used for creating the HTML content for the following component. This function will return the React elements which will be converted into the DOM elements. These should be a pure function and should not change the state while returning the elements. For more info on pure functions, check out this

[@react.component]
	let make = (~name) => {
	  // the whole body of this method comes under render lifecycle.
	  
	  name -> React.string;
	};

render.re

componentDidMount — This lifecycle method is called mostly for fetching some data or manipulating the DOM after the component is rendered, you can update the state based on the computations which you have performed in this method. This is only called after the first render of the component, for successive render check other lifecycle methods.

[@react.component]
	let make = (~name: string) => {
	  let (counter, setCounter) = React.useState(() => 0);
	  
	  // Enter any thing you want to enter in componentDidMount.
	  React.useEffect1(
	    () => {
	      setCounter(_ => counter + 1);
	      None
	    },
	    [||] // This is the key as this effect will be independent of any change in props.
	  );
	  
	  "counter is rendered only 1 time" -> React.string;
	}

componentDidMount.re

Lifecycle methods called while updating the component

Below listed lifecycle methods are called whenever there is a change in state or props. These lifecycle methods are called on every re-render.

  • Initialization
  • Mounting
  • Updating
  • Unmounting
[@react.component]
	let make = (~name) => name -> React.string;
	

	// If you want to shallow compare the props then use React.memo
	let make = React.memo(make);
	

	// If you want to custom compare the nested props then use React.memoCustomCompareProps
	let deepCompare = (nextProps, currentProps) => nextProps === currentProps;
	

	let make = React.memoCustomCompareProps(
	  make,
	  (nextProps, currentProps) => {
	    let result = deepCompare(nextProps, currentProps);
	    result;
	  }
	);

shouldComponentUpdate.re

componentDidUpdate — This lifecycle method is called after every re-render except for the first one. This lifecycle is generally used for doing any computation like network requests, event listener on the basis of change in props. Make sure to compare the props while updating the state, otherwise it will be stuck in infinite re-render.

[@react.component]
	let make = (~name, ~) => {
	  let (counter, setCounter) => React.useState(() => 0);
	  
	  // This will allow the change of the state/props only if certain props are passed or changed to.
	  React.useEffect1(
	    () => {
	      if (name === "componentDidUpdate") {
	        setCounter(_ => counter + 1);
	        None
	      }
	    },
	    [|name|] // Here we are listing dependency on which component will be re-rendered.
	  );
	  
	  (name ++ "is called " ++ counter -> string_of_int ++ " times.") -> React.string;
	};

componentDidUpdate.re

Lifecycle methods called while unmounting the component

These lifecycle methods are called when the component is removed from the DOM.

componentWillUnmount — This lifecycle method is called to do all the cleanup like removing the subscriptions or event listeners on the component. This lifecycle method is just called before the component is unmounted.

[@react.component]
	let make = () => {
	  let (counter, setCounter) = React.useState(() => 0);
	  
	  React.useEffect(() => {
	    let clearTimeout = Js.Global.setTimeout(() => setCounter(_ => counter + 1), 500);
	    
	    Some(Js.Global.clearTimeout(clearTimeout)) // This will be called when the component will be un-mounted
	  });
	  ("Counter is updated " ++ counter -> string_of_int ++ " times.") -> React.string;
	};

componentWillUnMount.re

Lifecycle methods called for error handling in components

These lifecycle methods are used to handle the error whenever any lifecycle method throws an error.

Right now, react team hasn’t created any hooks for error handling, but they have listed that they will be added soon. More info here.

Conclusion

Above is a quick guide for the transition from ReasonReact.reactClass (Reason React component type before hooks) to React.Element(Reason React upgraded component implementing hooks). You can read more about the hooks here. There are a bunch of other hooks listed here. Open source community has started creating a bunch of custom hooks to solve the generic issues. You can create your own custom hook (check this for the custom hook)

For any query, you can comment below :).

Thanks for reading :).

Recommended Reading

How to Add Spinners and Notifications to React app

Learn React and React Hooks with Java Code

How to build a multilingual website in Next.js

#reactjs #javascript

What is GEEK

Buddha Community

Implementing React Life Cycles Using Reason React Hooks
Autumn  Blick

Autumn Blick

1598839687

How native is React Native? | React Native vs Native App Development

If you are undertaking a mobile app development for your start-up or enterprise, you are likely wondering whether to use React Native. As a popular development framework, React Native helps you to develop near-native mobile apps. However, you are probably also wondering how close you can get to a native app by using React Native. How native is React Native?

In the article, we discuss the similarities between native mobile development and development using React Native. We also touch upon where they differ and how to bridge the gaps. Read on.

A brief introduction to React Native

Let’s briefly set the context first. We will briefly touch upon what React Native is and how it differs from earlier hybrid frameworks.

React Native is a popular JavaScript framework that Facebook has created. You can use this open-source framework to code natively rendering Android and iOS mobile apps. You can use it to develop web apps too.

Facebook has developed React Native based on React, its JavaScript library. The first release of React Native came in March 2015. At the time of writing this article, the latest stable release of React Native is 0.62.0, and it was released in March 2020.

Although relatively new, React Native has acquired a high degree of popularity. The “Stack Overflow Developer Survey 2019” report identifies it as the 8th most loved framework. Facebook, Walmart, and Bloomberg are some of the top companies that use React Native.

The popularity of React Native comes from its advantages. Some of its advantages are as follows:

  • Performance: It delivers optimal performance.
  • Cross-platform development: You can develop both Android and iOS apps with it. The reuse of code expedites development and reduces costs.
  • UI design: React Native enables you to design simple and responsive UI for your mobile app.
  • 3rd party plugins: This framework supports 3rd party plugins.
  • Developer community: A vibrant community of developers support React Native.

Why React Native is fundamentally different from earlier hybrid frameworks

Are you wondering whether React Native is just another of those hybrid frameworks like Ionic or Cordova? It’s not! React Native is fundamentally different from these earlier hybrid frameworks.

React Native is very close to native. Consider the following aspects as described on the React Native website:

  • Access to many native platforms features: The primitives of React Native render to native platform UI. This means that your React Native app will use many native platform APIs as native apps would do.
  • Near-native user experience: React Native provides several native components, and these are platform agnostic.
  • The ease of accessing native APIs: React Native uses a declarative UI paradigm. This enables React Native to interact easily with native platform APIs since React Native wraps existing native code.

Due to these factors, React Native offers many more advantages compared to those earlier hybrid frameworks. We now review them.

#android app #frontend #ios app #mobile app development #benefits of react native #is react native good for mobile app development #native vs #pros and cons of react native #react mobile development #react native development #react native experience #react native framework #react native ios vs android #react native pros and cons #react native vs android #react native vs native #react native vs native performance #react vs native #why react native #why use react native

What are hooks in React JS? - INFO AT ONE

In this article, you will learn what are hooks in React JS? and when to use react hooks? React JS is developed by Facebook in the year 2013. There are many students and the new developers who have confusion between react and hooks in react. Well, it is not different, react is a programming language and hooks is a function which is used in react programming language.
Read More:- https://infoatone.com/what-are-hooks-in-react-js/

#react #hooks in react #react hooks example #react js projects for beginners #what are hooks in react js? #when to use react hooks

Hayden Slater

1599277908

Validating React Forms With React-Hook-Form

Validating inputs is very often required. For example, when you want to make sure two passwords inputs are the same, an email input should in fact be an email or that the input is not too long. This is can be easily done using React Hook From. In this article, I will show you how.

Required Fields

The most simple, yet very common, validation is to make sure that an input component contains input from the user. React Hook Form basic concept is to register input tags to the form by passing register() to the tag’s ref attribute. As we can see here:

#react-native #react #react-hook-form #react-hook

Erna  Herzog

Erna Herzog

1626748440

Build a React Accordion from Scratch Using React Hooks and No Extra Dependencies

Follow these step-by-step instructions to create an animated accordion component in React.js using React Hooks and CSS.

🗂 DOWNLOADS 🗂

https://gum.co/AEeem

🔗 HELPFUL RESOURCES 🔗

React DOM Elements: https://reactjs.org/docs/dom-elements.html

Overview of dangerouslySetInnerHTML: https://react-cn.github.io/react/tips/dangerously-set-inner-html.html

How to prevent XSS attacks when using dangerouslySetInnerHTML in React: https://dev.to/jam3/how-to-prevent-xss-attacks-when-using-dangerouslysetinnerhtml-in-react-1464

Hooks API Reference: https://reactjs.org/docs/hooks-reference.html

Visual Studio Code: https://code.visualstudio.com/

#react #react hooks #react accordion #css #react.js

The Ugly Side of React Hooks

In this post, I will share my own point of view about React Hooks, and as the title of this post implies, I am not a big fan.

Let’s break down the motivation for ditching classes in favor of hooks, as described in the official React’s docs.

Motivation #1: Classes are confusing

we’ve found that classes can be a large barrier to learning React. You have to understand how "this"_ works in JavaScript, which is very different from how it works in most languages. You have to remember to bind the event handlers. Without unstable syntax proposals, the code is very verbose […] The distinction between function and class components in React and when to use each one leads to disagreements even between experienced React developers._

Ok, I can agree that

thiscould be a bit confusing when you are just starting your way in Javascript, but arrow functions solve the confusion, and calling a_stage 3_feature that is already being supported out of the box by Typescript, an “unstable syntax proposal”, is just pure demagoguery. React team is referring to theclass fieldsyntax, a syntax that is already being vastly used and will probably soon be officially supported

class Foo extends React.Component {
  onPress = () => {
    console.log(this.props.someProp);
  }

  render() {
    return <Button onPress={this.onPress} />
  }
}

As you can see, by using a class field arrow function, you don’t need to bind anything in the constructor, and

this will always point to the correct context.

And if classes are confusing, what can we say about the new hooked functions? A hooked function is not a regular function, because it has state, it has a weird looking

this(aka_useRef_), and it can have multiple instances. But it is definitely not a class, it is something in between, and from now on I will refer to it as aFunclass. So, are those Funclasses going to be easier for human and machines? I am not sure about machines, but I really don’t think that Funclasses are conceptually easier to understand than classes. Classes are a well known and thought out concept, and every developer is familiar with the concept ofthis, even if in javascript it’s a bit different. Funclasses on the other hand, are a new concept, and a pretty weird one. They feel much more magical, and they rely too much on conventions instead of a strict syntax. You have to follow somestrict and weird rules, you need to be careful of where you put your code, and there are many pitfalls. Telling me to avoid putting a hook inside anifstatement, because the internal mechanism of hooks is based on call order, is just insane! I would expect something like this from a half baked POC library, not from a well known library like React. Be also prepared for some awful naming like useRef (a fancy name forthis),useEffect ,useMemo,useImperativeHandle(say whatt??) and more.

The syntax of classes was specifically invented in order to deal with the concept of multiple instances and the concept of an instance scope (the exact purpose of

this ). Funclasses are just a weird way of achieving the same goal, using the wrong puzzle pieces. Many people are confusing Funclasses with functional programming, but Funclasses are actually just classes in disguise. A class is a concept, not a syntax.

Oh, and about the last note:

The distinction between function and class components in React and when to use each one leads to disagreements even between experienced React developers

Until now, the distinction was pretty clear- if you needed a state or lifecycle methods, you used a class, otherwise it doesn’t really matter if you used a function or class. Personally, I liked the idea that when I stumbled upon a function component, I could immediately know that this is a “dumb component” without a state. Sadly, with the introduction of Funclasses, this is not the situation anymore.

#react #react-hooks #javascript #reactjs #react-native #react-hook #rethinking-programming #hackernoon-top-story