Managing State in React using Unstated Next

State is a foundational part of React applications, which means managing state is hugely important. Since the introduction of the Context API and then Hooks, managing state has been relatively easy since the Context API helps save us the stress of using Redux.

As a result, multiple state management libraries have been published to further facilitate state management with the Context API, and in this article, I’ll be looking into Unstated Next.

What is Unstated Next?

Unstated Next is a library built on React’s Context API that allows the sharing of state globally in our applications. Unstated Next has simple API methods, which can be used either as Hooks or component methods. In the subsequent sections, I’ll discuss the API methods and then build a simple demo to demonstrate how Unstated Next works.

Unstated Next can be installed from either Yarn or npm:

yarn add unstated-next 

// or

npm install unstated-next

What problems does Unstated Next solve ?

Since Unstated Next is built on the Context API, it solves the same problems that the Context API solves. Unstated Next allows us to:

  • Access parent state from child components
  • Avoid prop drilling

Unstated Next API methods

Unstated Next houses three API methods, and I’ll discuss each one briefly:

createContainer(ourHook)

The createContainer method is used to initialize context and takes as an argument the Hook whose state is to be shared globally. This context is traditionally assigned to a variable, as shown below:

import { createContainer } from 'unstated-next'

function ourHook() {}

let ourContext = createContainer(ourHook)
// ourContext == {Provider, useContainer}

The variable, in turn, returns a provider and useContainer method. The useContainer method can also be referred to as the consumer.

Provider method

The provider method, which is appended to the context, takes in an optional initial value to be rendered on the application’s first render and accepts a child component to be rendered. Here’s an example of its usage:

import { createContainer } from 'unstated-next'

...

function Component() {}

<OurContainer>
  <Component />
</Ourcontainer>

<OurContainer initialState={"initial value"} />
  <Component />
</Ourcontainer>

useContainer(ctx)

The useContainer(ctx) Hook takes in the context variable as an argument and is stored in a variable that will be used to access the global state. The useContainer(ctx) Hook is used in the component where state is to be accessed — in this case, the child component. This will be demonstrated in the next section.

import { useContainer } from "unstated-next"

function ChildComponent() {
  let activity = useContainer(OurContainer)
  return <input value={activity.value} onChange={activity.onChange} />
}

The above are the available API methods in the Unstated Next libraries, which are purely built on the React API. In the next section, I’ll be building a simple to-do app to demonstrate how the methods work.

Setup

Before we dive in too deep, let’s map out the project structure and the installation of the dependencies needed for our to-do app. We’ll start by creating our project folder.

mkdir unstated-todo-app && cd unstated-todo-app
mkdir public src src/components
cd public && touch index.html style.css
cd ../src && touch index.js
cd components && touch Todos.js

Next, we’ll initialize the directory and install the dependencies needed.

npm init -y
npm i react react-dom react-scripts unstated-next

Now it’s time to write the App rendering component in the index.js file.

index.js

This file houses the component responsible for rendering our Todo``s component. First, I’ll import the dependencies needed:

import React from "react";
import { render } from "react-dom";
import TodoList from "./Components/Todos";

Don’t fret, the TodoList component will be built after this. Next, we tell React to render our app on the div node with an identifier "root":

function App() {
  return (
    <>
      <h3> Unstated Todo App </h3>
      <hr />
      <TodoList />
    </>
  )
}

render(<App />, document.getElementById("root"))

Next, we’ll begin writing the Todo``s component.

Todos.js

The Todos component comprises a custom Hook which will be handling the state for our to-do app alongside some state methods and a component that lets us add and renders our to-do.

We’ll start off by creating our custom hook and initializing with two state objects:

import React, { useState } from "react";

function useTodos(initialstate = [{todo: "Test todo"}]) {
  let [todos, setTodo] = useState(initialstate)
  let [todo, setTodoItem] = useState("")

Our Hook useTodos() takes an initial to-do (which is optional) that is rendered when the app is loaded. It has two state objects: todos and todo. The todos state object is an array of all the to-dos in our app, while the todo state object is the to-do added to the todos array and has an initial value of an empty string.

The todo is set from the user input and then added to the todos array by means of a setTodo() method, which we’ll be looking at next.

 ...
  const handleInput = e => {
    setTodoItem(e.target.value)
  }

  const addTodo = e => {
    e.preventDefault()
    setTodo([...todos, {todo}])
    setTodoItem("")
  }

  const removeTodo = id => {
    const todoList = todos.filter(todo => todo.todo !== id)
    return setTodo(todoList)
  }

  return { todos, todo, addTodo, removeTodo, handleInput }

}
  1. The handleInput() method is used to set the todo state to the value the user inputs in the form by using the setTodoItem state handler.
  2. The addTodo() method adds the to-do item into the todos array by means of the setTodo([...todos, todo]) method. It then sets the todo state to an empty string.
  3. The removeTodo() method removes a to-do from the todos array.

Then, we return the values of the state and the Hook’s method so it can be accessible in our components.

Next, we’ll create a container from our useTodo() Hook. First, we’ll import the createContainer Hook from Unstated Next:

// After the react import
import { createContainer } from "unstated-next";

Then we create the container that will be used in our components. It gives us direct access to our app’s state and its method, as discussed in the previous section:

let Todos = createContainer(useTodos)

The container doesn’t do anything yet, and we haven’t built the components for the to-do. You guessed right — we’ll be building that next.

function Todo({ todo }) {
  let todosContainer = Todos.useContainer()
  return (
    <>     
      <ul className="w3-ul w3-card-4">
        <li key={todo.todo} className="w3-display-container" >
           {todo.todo}
           <span className="w3-button w3-transparent w3-display-right" onClick={() => todosContainer.removeTodo(todo.todo)}>&times;</span>
        </li>
      </ul>
    </>
  )
}

The component above is responsible for rendering the todo passed as a prop from an iteration of the todos array.

Next, we build the consumer component that displays the to-dos and let us add a to-do:

function DisplayTodos() {  
  let todosContainer = Todos.useContainer()
  return (
    <React.Fragment>
      <input type="text" className="w3-input w3-border w3-round" placeholder="Write an article" value={todosContainer.todo} onChange={todosContainer.handleInput} />
      <button onClick={todosContainer.addTodo} className="w3-button w3-round w3-black">Add Todo</button>
      <hr />
      {
        todosContainer.todos.map(todo => (
          <Todo todo={todo} />
        ))
      }
    </React.Fragment>
  )
}

On lines 8–12, we iterate over the todos array state and then pass each todo as a prop to the Todo component.

In the components above, the container is used from the variable todosContainer to allow access to the states and its methods, as can be seen in the render blocks of each component.

Next, we define a component that renders the consumer component DisplayTodos() under the context provider since nothing can be consumed without a provider 🙂

export default function TodoList() {
  return (
    <Todos.Provider>
      <DisplayTodos />
    </Todos.Provider>
  )
}

We make the component a default export since it has been imported to be rendered in the App component.

Running our app

With the completion of our app’s build process, we are yet to write the code for the index.html and style.css files. Let’s do that before we proceed:

index.html

<!DOCTYPE html>
<html lang="en">
<head>
  <meta charset="UTF-8">
  <meta name="viewport" content="width=device-width, initial-scale=1.0">
  <meta http-equiv="X-UA-Compatible" content="ie=edge">
  <link rel="stylesheet" href="https://www.w3schools.com/w3css/4/w3.css">
  <link rel="stylesheet" href="style.css" type="text/css">
  <title>Unstated-next Recipe App</title>
</head>
<body>
  <div id="root" class="w3-container"></div>
</body>
</html>

style.css

body {
  font-family: 'Gill Sans', 'Gill Sans MT', Calibri, 'Trebuchet MS', sans-serif;
  background-color: antiquewhite;
}

After that, let’s configure package.json so we can run our app. Under the scripts section, replace the code there with:

"start": "react-scripts start"

With that done, let’s start the app and view it live on [http://localhost:3000](http://localhost:3000):

npm run start

Here’s a demonstration of the app in use:

Our To-do App In Action

Conclusion

This article should give you a basic understanding of what Unstated Next is, its features, and how it works. The main takeaway is that you can use Unstated Next in place of the traditional React Context API Hooks and Redux.

Unstated Next is an excellent React library for managing state apps. However, be aware that there are cases in which the Context API, and thus Unstated Next, shouldn’t be used. The code used in this article can be found on GitHub.

Originally published by Abdulazeez Abdulazeez Adeshina at https://blog.logrocket.com

#reactjs #web-development #javascript

What is GEEK

Buddha Community

Managing State in React using Unstated Next
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

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

Trinity  Kub

Trinity Kub

1589991240

Using Unstated Next helps reduce stress when using Redux

State is a foundational part of React applications, which means managing state is hugely important. Since the introduction of the Context API and then Hooks, managing state has been relatively easy since the Context API helps save us the stress of using Redux.

As a result, multiple state management libraries have been published to further facilitate state management with the Context API, and in this article, I’ll be looking into Unstated Next.

What is Unstated Next?
Unstated Next is a library built on React’s Context API that allows the sharing of state globally in our applications. Unstated Next has simple API methods, which can be used either as Hooks or component methods. In the subsequent sections, I’ll discuss the API methods and then build a simple demo to demonstrate how Unstated Next works.

#react #react-native #react.js #unstated next

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

I am Developer

1597487472

Country State City Dropdown list in PHP MySQL PHP

Here, i will show you how to populate country state city in dropdown list in php mysql using ajax.

Country State City Dropdown List in PHP using Ajax

You can use the below given steps to retrieve and display country, state and city in dropdown list in PHP MySQL database using jQuery ajax onchange:

  • Step 1: Create Country State City Table
  • Step 2: Insert Data Into Country State City Table
  • Step 3: Create DB Connection PHP File
  • Step 4: Create Html Form For Display Country, State and City Dropdown
  • Step 5: Get States by Selected Country from MySQL Database in Dropdown List using PHP script
  • Step 6: Get Cities by Selected State from MySQL Database in DropDown List using PHP script

https://www.tutsmake.com/country-state-city-database-in-mysql-php-ajax/

#country state city drop down list in php mysql #country state city database in mysql php #country state city drop down list using ajax in php #country state city drop down list using ajax in php demo #country state city drop down list using ajax php example #country state city drop down list in php mysql ajax