Karim Aya

Karim Aya

1564106522

React Hooks: Understanding The Weird Parts

Originally published by Rajdeep Chandra at thecoderswag.com

React 16.8.xx is shipped with React Hooks feature support in which developers can build functional components which can have own local state and props. (OH WOW)

What is a Hook?

Hooks are functions that let you “hook into” React state and lifecycle features from function components. Hooks don’t work inside classes — they let you use React without classes.

Let’s see what are the out of the box hooks they have for us:

State Hook:

Here, useState is a Hook (we’ll talk about what this means in a moment). We call it inside a function component to add some local state to it. React will preserve this state between re-renders. useState returns a pair: the current state value and a function that lets you update it. You can call this function from an event handler or somewhere else. It’s similar to this.setState in a class, except it doesn’t merge the old and new state together.

Effect Hook:

You’ve likely performed data fetching, subscriptions, or manually changing the DOM from React components before. We call these operations “side effects” (or “effects” for short) because they can affect other components and can’t be done during rendering.

The Effect Hook, useEffect, adds the ability to perform side effects from a function component. It serves the same purpose as componentDidMountcomponentDidUpdate, and componentWillUnmount in React classes, but unified into a single API.

Rules of Hooks

Hooks are JavaScript functions, but they impose two additional rules:

  • Only call Hooks at the top level. Don’t call Hooks inside loops, conditions, or nested functions.
  • Only call Hooks from React function components. Don’t call Hooks from regular JavaScript functions. (There is just one other valid place to call Hooks — your own custom Hooks. We’ll learn about them in a moment.)

useContext Hook:

It lets you subscribe to React context without introducing nesting. For e.g when you want to use your logged-in data deep down to some of the nested components: For e.g:

const locale = useContext(LocaleContext);
const theme = useContext(ThemeContext);

useReducer Hook:

useReducer hook lets you manage local state of complex components with a reducer:

Custom Hook:

Sometimes, we want to reuse some stateful logic between components. Traditionally, there were two popular solutions to this problem: higher-order components and render props. Custom Hooks let you do this, but without adding more components to your tree.

Below is a custom Hook:

The above custom hook is called useFetch which can be used as a custom hooks by calling the below method in your component

Other Useful Reads

Check out other cool React.js articles in the dedicated section at this link

Conclusion

If you found this article helpful, it would mean a lot if you commented it and shared to help others find it! And feel free to leave a comment below.

Originally published by Rajdeep Chandra at thecoderswag.com

=======================================================

Thanks for reading :heart: If you liked this post, share it with all of your programming buddies! Follow me on Facebook | Twitter

Learn More

☞ Understanding TypeScript

☞ Typescript Masterclass & FREE E-Book

☞ React - The Complete Guide (incl Hooks, React Router, Redux)

☞ Modern React with Redux [2019 Update]

☞ The Complete React Developer Course (w/ Hooks and Redux)

☞ React JS Web Development - The Essentials Bootcamp

☞ React JS, Angular & Vue JS - Quickstart & Comparison

☞ The Complete React Js & Redux Course - Build Modern Web Apps

☞ React JS and Redux Bootcamp - Master React Web Development

#reactjs #web-development

What is GEEK

Buddha Community

React Hooks: Understanding The Weird Parts
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

Trinity  Kub

Trinity Kub

1593285480

Getting Started With React Hooks — Part 1

In this post I will try to explain how to use react hooks step by step from basics using a simple todo app.

This series assumes you already know to work with react, “create react app” and basic class components. i.e you have a basic understanding of how react works.

Lets Start

Create a new project using CRA

npx create-react-app todo-list-hooks
cd todo-list-hooks

Next i will be using bootstrap for some simple basic designs so lets install bootstrap package and include it

npm install bootstrap@next

Next open your src/index.js to add bootstrap

import '../node_modules/bootstrap/dist/css/bootstrap.min.css';

Next, we let’s clean up the default react stuff that comes so we have a clean working code.

//src/App.js

import React from 'react';
function App() {
  return (
    <div className="App">
      {/* // will add futher code here.. */}
    </div>
  );
}
export default App;

Now you should have a simple blank screen to work with on your browser.

Run your react app and see browser

npm start

Basic UI Setup

Lets add a nav bar and an add todo button and few list elements. I will be using all html from bootstrap

Add this code into App.js

//src/App.js

import React from 'react';
function App() {
  return (
    <div className="App">
      <nav className="navbar navbar-light bg-light">
        <div className="container-fluid">
          <a className="navbar-brand" href="#">Navbar</a>
          <ul class="nav">
            <li class="nav-item">
            <button type="button" className="btn btn-primary">Add Todo</button>
            </li>
          </ul>
        </div>
      </nav>
      <div className="container-fluid">
        <div className="row">
          <ul className="list-group">
            <li className="list-group-item d-flex justify-content-between align-items-center">
              Cras justo odio
              <span class="badge bg-danger rounded-pill">
                &times;
              </span>
            </li>
            <li className="list-group-item d-flex justify-content-between align-items-center">Dapibus ac facilisis in</li>
            <li className="list-group-item d-flex justify-content-between align-items-center">Morbi leo risus</li>
            <li className="list-group-item d-flex justify-content-between align-items-center">Porta ac consectetur ac</li>
            <li className="list-group-item d-flex justify-content-between align-items-center">Vestibulum at eros</li>
          </ul>
        </div>
      </div>
    </div>
  );
}
export default App;

You should have a screen like this for now

#hooks #reactjs #react #react-training #react hooks #programming

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