Cristian Vasta

Cristian Vasta

1610455020

Simple State Stores using Immer and React Hooks

pullstate

Ridiculously simple state stores with performant retrieval anywhere in your React tree using the wonderful concept of React hooks!

  • ~7KB minified and gzipped! (excluding Immer and React)
  • Built with Typescript, providing a great dev experience if you’re using it too
  • Uses immer for state updates - easily and safely mutate your state directly!
  • NEW - Create async actions and use React hooks or <Suspense/> to have complete control over their UI states!

Originally inspired by the now seemingly abandoned library - bey. Although substantially different now- with Server-side rendering and Async Actions built in! Bey was in turn inspired by react-copy-write.

Try out a quick example:

Edit Pullstate Client-only Example

🎉 New documentation site is live!


Let’s dive right in

This is taken directly from the documentation site, to give you a quick overview of Pullstate here on github. Be sure to check out the site to learn more.

To start off, install pullstate.

yarn add pullstate

Create a store

Define the first state store, by passing an initial state to new Store():

import { Store } from "pullstate";

export const UIStore = new Store({
  isDarkMode: true,
});

Read our store’s state

Then, in React, we can start using the state of that store using a simple hook useState():

import * as React from "react";
import { UIStore } from "./UIStore";

export const App = () => {
  const isDarkMode = UIStore.useState(s => s.isDarkMode);

  return (
    <div
      style={{
        background: isDarkMode ? "black" : "white",
        color: isDarkMode ? "white" : "black",
      }}>
      <h1>Hello Pullstate</h1>
    </div>
  );
};

The argument to useState() over here (s => s.isDarkMode), is a selection function that ensures we select only the state that we actually need for this component. This is a big performance booster, as we only listen for changes (and if changed, re-render the component) on the exact returned values - in this case, simply the value of isDarkMode.


Add interaction (update state)

Great, so we are able to pull our state from UIStore into our App. Now lets add some basic interaction with a <button>:

  return (
    <div
      style={{
        background: isDarkMode ? "black" : "white",
        color: isDarkMode ? "white" : "black",
      }}>
      <h1>Hello Pullstate</h1>
      <button
        onClick={() =>
          UIStore.update(s => {
            s.isDarkMode = !isDarkMode;
          })
        }>
        Toggle Dark Mode
      </button>
    </div>
  );

Notice how we call update() on UIStore, inside which we directly mutate the store’s state. This is all thanks to the power of immer, which you can check out here.

Another pattern, which helps to illustrate this further, would be to actually define the action of toggling dark mode to a function on its own:

function toggleMode(s) {
  s.isDarkMode = !s.isDarkMode;
}

// ...in our <button> code
<button onClick={() => UIStore.update(toggleMode)}>Toggle Dark Mode</button>

Basically, to update our app’s state all we need to do is create a function (inline arrow function or regular) which takes the current store’s state and mutates it to whatever we’d like the next state to be.

Omnipresent state updating

Something interesting to notice at this point is that we are just importing UIStore directly and running update() on it:

import { UIStore } from "./UIStore";

// ...in our <button> code
<button onClick={() => UIStore.update(toggleMode)}>Toggle Dark Mode</button>

And our components are being updated accordingly. We have freed our app’s state from the confines of the component! This is one of the main advantages of Pullstate - allowing us to separate our state concerns from being locked in at the component level and manage things easily at a more global level from which our components listen and react (through our useStoreState() hooks).

Download Details:

Author: lostpebble

Demo: https://lostpebble.github.io/pullstate/

Source Code: https://github.com/lostpebble/pullstate

#react #reactjs #javascript

What is GEEK

Buddha Community

Simple State Stores using Immer and 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

I am Developer

1597487833

Country State City Drop Down List using Ajax in Laravel

Here, i will show you how to create dynamic depedent country state city dropdown list using ajax in laravel.

Country State City Dropdown List using Ajax in php Laravel

Follow Below given steps to create dynamic dependent country state city dropdown list with jQuery ajax in laravel:

  • Step 1: Install Laravel App
  • Step 2: Add Database Details
  • Step 3: Create Country State City Migration and Model File
  • Step 4: Add Routes For Country State City
  • Step 5: Create Controller For Fetch Country State City
  • Step 6: Create Blade File For Show Dependent Country State City in Dropdown
  • Step 7: Run Development Server

https://www.tutsmake.com/ajax-country-state-city-dropdown-in-laravel/

#how to create dynamic dropdown list using laravel dynamic select box in laravel #laravel-country state city package #laravel country state city drop down #dynamic dropdown country city state list in laravel using ajax #country state city dropdown list using ajax in php laravel #country state city dropdown list using ajax in laravel demo

Slava Birch

Slava Birch

1621742803

Reuse React hooks in state sharing

Hi guys, today I’m going to talk about how to complete your code with one hook that will complete the puzzle!

The release of React 16.8 was a gift and a blessing, hooks were a great tool for managing the state of components. And having met with amicability, the community began to create new hooks based on standard ones for asynchronous operations, for interacting with external logic, and many many others.

Hooks let you use state and other React features without writing a class.
You can also build your own Hooks to share reusable stateful logic between components.

But (I’m sure) it became a chagrin for everyone that hooks can only store data at the component level. And therefore components can share their state only with children.

And that’s the problem.

We have enough hooks to describe any logic, but there is no way to use their state together between a group of unrelated components.

You can see that Recoil, Redux, MobX, and the standard React hooks do the same thing - managing reactive state.
But why do we need to use in our applications a way of describing logic on hooks in components and on an external application state management system?

I suggest you try the simplest way to share the state described in hooks with other unrelated components on the page.

The useBetween hook.

And this is just one hook, with the only one call argument - a custom hook, the result of which will be shared by everyone.

For example, let’s describe a custom hook that supplies a hash from the browser’s address bar. The hook subscribes to changes to the browser hash through the window event.

// router.shared.ts
import { useState, useCallback, useEffect } from "react";
import { useBetween } from "use-between";

const useRouter = () => {
  const [hash, setHash] = useState("");

  const syncHash = useCallback(() => {
    setHash(window.location.hash);
  }, [setHash]);

  useEffect(() => {
    syncHash();
    window.addEventListener("hashchange", syncHash);
    return () => {
      window.removeEventListener("hashchange", syncHash);
    };
  }, [syncHash]);

  return {
    hash
  };
};

export const useSharedRouter = () => useBetween(useRouter);

In the last line of the example, we used a call to useBetween passing a custom useRouter hook as an argument, and thus created a new useSharedRouter hook - a shared router for all components that will use it.

const Hash = () => {
  const { hash } = useSharedRouter();
  return (
    <p>Location hash: {hash}</p>
  )
}

export const App = () => (
  <>
    <Hash />
    <Hash />
    <Hash />

    <a href="#hash-1">hash-1</a>
    <a href="#hash-2">hash-2</a>
  </>
)

Edit Counter with useBetween

In this example, the router will be created once and will be used for all the Hash components. Every time the hash of the navigation bar address changes, all components using useSharedRouter will be updated!

We used the standard React hooks that are familiar and understandable to everyone to create a shared state between any components using just one external hook useBetween.

Everything will be installed simply npm i use-between and you can use and enjoy, and for my taste, the easiest way to share the state in React!

If you like this idea and would like to use it, please join to us. It will be your first contribution!

use-between github repository and documentation.

Enjoy and Happy Coding!

#react #react-hooks #state-sharing #use-between #javascript #webdev