<?xml version="1.0" encoding="UTF-8"?>
<rss version="2.0" xmlns:atom="http://www.w3.org/2005/Atom" xmlns:dc="http://purl.org/dc/elements/1.1/">
  <channel>
    <title>DEV Community: Paritosh Gupta</title>
    <description>The latest articles on DEV Community by Paritosh Gupta (@paritoshg).</description>
    <link>https://dev.to/paritoshg</link>
    <image>
      <url>https://media2.dev.to/dynamic/image/width=90,height=90,fit=cover,gravity=auto,format=auto/https:%2F%2Fdev-to-uploads.s3.amazonaws.com%2Fuploads%2Fuser%2Fprofile_image%2F461412%2F3e1f6cec-25aa-4d03-9896-c31f8ad5d629.png</url>
      <title>DEV Community: Paritosh Gupta</title>
      <link>https://dev.to/paritoshg</link>
    </image>
    <atom:link rel="self" type="application/rss+xml" href="https://dev.to/feed/paritoshg"/>
    <language>en</language>
    <item>
      <title>React Hooks</title>
      <dc:creator>Paritosh Gupta</dc:creator>
      <pubDate>Mon, 17 Jun 2024 09:41:16 +0000</pubDate>
      <link>https://dev.to/paritoshg/react-hooks-43kk</link>
      <guid>https://dev.to/paritoshg/react-hooks-43kk</guid>
      <description>&lt;p&gt;React Hooks were introduced in React 16.8 to provide functional components with features previously exclusive to class components, such as state and lifecycle methods. Hooks allow for cleaner, more modular code, making it easier to share logic across components without relying on higher-order components or render props.&lt;/p&gt;

&lt;p&gt;&lt;a href="https://media.dev.to/cdn-cgi/image/width=800%2Cheight=%2Cfit=scale-down%2Cgravity=auto%2Cformat=auto/https%3A%2F%2Fdev-to-uploads.s3.amazonaws.com%2Fuploads%2Farticles%2F7vefzri0i4ehe4x9426f.png" class="article-body-image-wrapper"&gt;&lt;img src="https://media.dev.to/cdn-cgi/image/width=800%2Cheight=%2Cfit=scale-down%2Cgravity=auto%2Cformat=auto/https%3A%2F%2Fdev-to-uploads.s3.amazonaws.com%2Fuploads%2Farticles%2F7vefzri0i4ehe4x9426f.png" alt="Image description" width="800" height="450"&gt;&lt;/a&gt;&lt;/p&gt;

&lt;p&gt;&lt;strong&gt;Basic Hooks&lt;/strong&gt;&lt;/p&gt;

&lt;p&gt;&lt;strong&gt;useState&lt;/strong&gt;&lt;/p&gt;

&lt;p&gt;useState is a Hook that allows you to add state to functional components. It returns a state variable and a function to update it.&lt;/p&gt;

&lt;p&gt;Example:&lt;/p&gt;

&lt;p&gt;`import React, { useState } from 'react';&lt;/p&gt;

&lt;p&gt;function Counter() {&lt;br&gt;
  const [count, setCount] = useState(0);&lt;/p&gt;

&lt;p&gt;return (&lt;br&gt;
    &lt;/p&gt;
&lt;br&gt;
      &lt;p&gt;You clicked {count} times&lt;/p&gt;
&lt;br&gt;
       setCount(count + 1)}&amp;gt;Click me&lt;br&gt;
    &lt;br&gt;
  );&lt;br&gt;
}

&lt;p&gt;export default Counter;`&lt;/p&gt;

&lt;p&gt;&lt;strong&gt;useEffect&lt;/strong&gt;&lt;/p&gt;

&lt;p&gt;useEffect is a Hook for performing side effects in functional components, such as fetching data, directly updating the DOM, and setting up subscriptions. It runs after the render by default.&lt;/p&gt;

&lt;p&gt;Example:&lt;/p&gt;

&lt;p&gt;`import React, { useState, useEffect } from 'react';&lt;/p&gt;

&lt;p&gt;function Timer() {&lt;br&gt;
  const [count, setCount] = useState(0);&lt;/p&gt;

&lt;p&gt;useEffect(() =&amp;gt; {&lt;br&gt;
    const interval = setInterval(() =&amp;gt; {&lt;br&gt;
      setCount(count + 1);&lt;br&gt;
    }, 1000);&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;return () =&amp;gt; clearInterval(interval); // Cleanup on unmount
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;

&lt;p&gt;}, [count]); // Dependency array&lt;/p&gt;

&lt;p&gt;return &lt;/p&gt;{count};&lt;br&gt;
}

&lt;p&gt;export default Timer;`&lt;/p&gt;

&lt;p&gt;&lt;strong&gt;Advanced Hooks&lt;/strong&gt;&lt;/p&gt;

&lt;p&gt;&lt;strong&gt;useContext&lt;/strong&gt;&lt;br&gt;
useContext allows you to consume context in a functional component, providing a way to share values like themes or authenticated users across the component tree without prop drilling.&lt;/p&gt;

&lt;p&gt;Example:&lt;/p&gt;

&lt;p&gt;`import React, { useContext, createContext } from 'react';&lt;/p&gt;

&lt;p&gt;const ThemeContext = createContext('light');&lt;/p&gt;

&lt;p&gt;function ThemedButton() {&lt;br&gt;
  const theme = useContext(ThemeContext);&lt;/p&gt;

&lt;p&gt;return I am a {theme} button;&lt;br&gt;
}&lt;/p&gt;

&lt;p&gt;function App() {&lt;br&gt;
  return (&lt;br&gt;
    &lt;br&gt;
      &lt;br&gt;
    &lt;br&gt;
  );&lt;br&gt;
}&lt;/p&gt;

&lt;p&gt;export default App;`&lt;/p&gt;

&lt;p&gt;&lt;strong&gt;useReducer&lt;/strong&gt;&lt;/p&gt;

&lt;p&gt;useReducer is used for state management in more complex scenarios, similar to Redux. It is useful for managing state transitions.&lt;/p&gt;

&lt;p&gt;Example:&lt;/p&gt;

&lt;p&gt;`import React, { useReducer } from 'react';&lt;/p&gt;

&lt;p&gt;const initialState = { count: 0 };&lt;/p&gt;

&lt;p&gt;function reducer(state, action) {&lt;br&gt;
  switch (action.type) {&lt;br&gt;
    case 'increment':&lt;br&gt;
      return { count: state.count + 1 };&lt;br&gt;
    case 'decrement':&lt;br&gt;
      return { count: state.count - 1 };&lt;br&gt;
    default:&lt;br&gt;
      throw new Error();&lt;br&gt;
  }&lt;br&gt;
}&lt;/p&gt;

&lt;p&gt;function Counter() {&lt;br&gt;
  const [state, dispatch] = useReducer(reducer, initialState);&lt;/p&gt;

&lt;p&gt;return (&lt;br&gt;
    &lt;/p&gt;
&lt;br&gt;
      &lt;p&gt;Count: {state.count}&lt;/p&gt;
&lt;br&gt;
       dispatch({ type: 'increment' })}&amp;gt;+&lt;br&gt;
       dispatch({ type: 'decrement' })}&amp;gt;-&lt;br&gt;
    &lt;br&gt;
  );&lt;br&gt;
}

&lt;p&gt;export default Counter;`&lt;/p&gt;

&lt;p&gt;&lt;strong&gt;useRef&lt;/strong&gt;&lt;/p&gt;

&lt;p&gt;useRef returns a mutable ref object whose .current property is initialized to the passed argument. It can persist across renders.&lt;/p&gt;

&lt;p&gt;Example:&lt;/p&gt;

&lt;p&gt;`import React, { useRef } from 'react';&lt;/p&gt;

&lt;p&gt;function TextInput() {&lt;br&gt;
  const inputEl = useRef(null);&lt;/p&gt;

&lt;p&gt;const handleClick = () =&amp;gt; {&lt;br&gt;
    inputEl.current.focus();&lt;br&gt;
  };&lt;/p&gt;

&lt;p&gt;return (&lt;br&gt;
    &lt;/p&gt;
&lt;br&gt;
      &lt;br&gt;
      Focus the input&lt;br&gt;
    &lt;br&gt;
  );&lt;br&gt;
}

&lt;p&gt;export default TextInput;`&lt;/p&gt;

&lt;p&gt;&lt;strong&gt;useMemo&lt;/strong&gt;&lt;/p&gt;

&lt;p&gt;useMemo is used to memoize expensive calculations, returning a memoized value only if the dependencies have changed.&lt;/p&gt;

&lt;p&gt;Example:&lt;/p&gt;

&lt;p&gt;`import React, { useState, useMemo } from 'react';&lt;/p&gt;

&lt;p&gt;function ExpensiveCalculationComponent({ num }) {&lt;br&gt;
  const calculate = (num) =&amp;gt; {&lt;br&gt;
    console.log('Calculating...');&lt;br&gt;
    return num * 2;&lt;br&gt;
  };&lt;/p&gt;

&lt;p&gt;const memoizedValue = useMemo(() =&amp;gt; calculate(num), [num]);&lt;/p&gt;

&lt;p&gt;return &lt;/p&gt;The result is: {memoizedValue};&lt;br&gt;
}

&lt;p&gt;function App() {&lt;br&gt;
  const [num, setNum] = useState(1);&lt;/p&gt;

&lt;p&gt;return (&lt;br&gt;
    &lt;/p&gt;
&lt;br&gt;
       setNum(e.target.value)} /&amp;gt;&lt;br&gt;
      &lt;br&gt;
    &lt;br&gt;
  );&lt;br&gt;
}

&lt;p&gt;export default App;`&lt;/p&gt;

&lt;p&gt;&lt;strong&gt;useCallback&lt;/strong&gt;&lt;br&gt;
useCallback returns a memoized callback function that only changes if one of the dependencies changes. It is useful for preventing unnecessary re-renders of child components.&lt;/p&gt;

&lt;p&gt;Example:&lt;/p&gt;

&lt;p&gt;`import React, { useState, useCallback } from 'react';&lt;/p&gt;

&lt;p&gt;function Button({ handleClick }) {&lt;br&gt;
  return Click me;&lt;br&gt;
}&lt;/p&gt;

&lt;p&gt;function App() {&lt;br&gt;
  const [count, setCount] = useState(0);&lt;/p&gt;

&lt;p&gt;const handleClick = useCallback(() =&amp;gt; {&lt;br&gt;
    setCount(count + 1);&lt;br&gt;
  }, [count]);&lt;/p&gt;

&lt;p&gt;return (&lt;br&gt;
    &lt;/p&gt;
&lt;br&gt;
      &lt;p&gt;Count: {count}&lt;/p&gt;
&lt;br&gt;
      &lt;br&gt;
    &lt;br&gt;
  );&lt;br&gt;
}

&lt;p&gt;export default App;`&lt;br&gt;
&lt;strong&gt;Custom Hooks&lt;/strong&gt;&lt;br&gt;
Custom Hooks are JavaScript functions that start with "use" and can call other Hooks. They enable the reuse of stateful logic between components.&lt;/p&gt;

&lt;p&gt;Example:&lt;/p&gt;

&lt;p&gt;`import React, { useState, useEffect } from 'react';&lt;/p&gt;

&lt;p&gt;function useFetch(url) {&lt;br&gt;
  const [data, setData] = useState(null);&lt;br&gt;
  const [loading, setLoading] = useState(true);&lt;/p&gt;

&lt;p&gt;useEffect(() =&amp;gt; {&lt;br&gt;
    async function fetchData() {&lt;br&gt;
      const response = await fetch(url);&lt;br&gt;
      const result = await response.json();&lt;br&gt;
      setData(result);&lt;br&gt;
      setLoading(false);&lt;br&gt;
    }&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;fetchData();
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;

&lt;p&gt;}, [url]);&lt;/p&gt;

&lt;p&gt;return { data, loading };&lt;br&gt;
}&lt;/p&gt;

&lt;p&gt;function DataComponent({ url }) {&lt;br&gt;
  const { data, loading } = useFetch(url);&lt;/p&gt;

&lt;p&gt;if (loading) return &lt;/p&gt;Loading...;&lt;br&gt;
  return {JSON.stringify(data)};&lt;br&gt;
}

&lt;p&gt;function App() {&lt;br&gt;
  return ;&lt;br&gt;
}&lt;/p&gt;

&lt;p&gt;export default App;&lt;br&gt;
`&lt;strong&gt;Conclusion&lt;/strong&gt;&lt;br&gt;
React Hooks provide a powerful and flexible way to manage state and side effects in functional components. By understanding and leveraging the various hooks, such as useState, useEffect, useContext, useReducer, useRef, useMemo, and useCallback, as well as creating custom hooks, React developers can write cleaner, more maintainable code. This approach fosters better code reuse and simplifies complex component logic, enhancing the overall development experience.&lt;/p&gt;

</description>
    </item>
    <item>
      <title>JavaScript API using Cylon.js to interact with IBM Watson cloud</title>
      <dc:creator>Paritosh Gupta</dc:creator>
      <pubDate>Sat, 04 Mar 2023 05:46:25 +0000</pubDate>
      <link>https://dev.to/paritoshg/javascript-api-using-cylonjs-to-interact-with-ibm-watson-cloud-285c</link>
      <guid>https://dev.to/paritoshg/javascript-api-using-cylonjs-to-interact-with-ibm-watson-cloud-285c</guid>
      <description>&lt;p&gt;Cylon is a Javascript framework with support for over 43 platforms for robotics, physical computing and internet of things. Cylon can run directly in the browser (through browserify) or any Chrome-connected app, and support http/https, mqtt and socket.io plugins.&lt;/p&gt;

&lt;p&gt;Here is an example of how one can write a JavaScript API using Cylon.js to interact with IBM Watson cloud services:&lt;/p&gt;

&lt;p&gt;`// Require the cylon module and watson developer cloud module&lt;br&gt;
var Cylon = require('cylon');&lt;br&gt;
var watson = require('watson-developer-cloud');&lt;/p&gt;

&lt;p&gt;// Define the Watson speech-to-text service credentials&lt;br&gt;
var speechToText = watson.speech_to_text({&lt;br&gt;
  username: 'your_username_here',&lt;br&gt;
  password: 'your_password_here',&lt;br&gt;
  version: 'v1'&lt;br&gt;
});&lt;/p&gt;

&lt;p&gt;// Define the robot&lt;br&gt;
Cylon.robot({&lt;br&gt;
  // Define connections to hardware devices&lt;br&gt;
  connections: {&lt;br&gt;
    watson: { adaptor: 'watson', speech_to_text: speechToText }&lt;br&gt;
  },&lt;/p&gt;

&lt;p&gt;// Define API&lt;br&gt;
  work: function(my) {&lt;br&gt;
    // Define functions to be exposed by the API&lt;br&gt;
    my.apiFunctions = {&lt;br&gt;
      transcribeAudio: function(audioFile, callback) {&lt;br&gt;
        // Use the Watson speech-to-text service to transcribe the audio file&lt;br&gt;
        var params = {&lt;br&gt;
          audio: audioFile,&lt;br&gt;
          content_type: 'audio/wav',&lt;br&gt;
          model: 'en-US_BroadbandModel'&lt;br&gt;
        };&lt;br&gt;
        my.watson.speech_to_text.recognize(params, function(err, res) {&lt;br&gt;
          if (err) {&lt;br&gt;
            console.log(err);&lt;br&gt;
            callback(err, null);&lt;br&gt;
          } else {&lt;br&gt;
            console.log(JSON.stringify(res, null, 2));&lt;br&gt;
            callback(null, res);&lt;br&gt;
          }&lt;br&gt;
        });&lt;br&gt;
      }&lt;br&gt;
    };&lt;br&gt;
  }&lt;br&gt;
}).start();&lt;/p&gt;

&lt;p&gt;// Expose API functions&lt;br&gt;
module.exports = function(callback) {&lt;br&gt;
  Cylon.api({&lt;br&gt;
    host: '0.0.0.0',&lt;br&gt;
    port: '3000',&lt;br&gt;
    ssl: false,&lt;br&gt;
    auth: false,&lt;br&gt;
    CORS: false,&lt;br&gt;
    logger: false,&lt;br&gt;
    // Expose the apiFunctions object as the API&lt;br&gt;
    api: Cylon.robots[0].apiFunctions&lt;br&gt;
  });&lt;/p&gt;

&lt;p&gt;// Call the callback function to indicate that the API is ready&lt;br&gt;
  callback();&lt;br&gt;
};`&lt;/p&gt;

&lt;p&gt;In this example, we first require the watson-developer-cloud module and create a speechToText object with the credentials for the Watson speech-to-text service.&lt;/p&gt;

&lt;p&gt;We then define a robot with a connection to the Watson service using the watson adaptor. Inside the work function, we define an object called apiFunctions that contains a single function called transcribeAudio, which takes an audio file and a callback function as parameters. This function uses the recognize method of the Watson speech-to-text service to transcribe the audio file and calls the callback function with the result or an error.&lt;/p&gt;

&lt;p&gt;We then use the Cylon.api function to expose the apiFunctions object as an API on port 3000. Finally, we export a function that takes a callback parameter, which is called when the API is ready. This allows us to start the API server asynchronously.&lt;/p&gt;

</description>
      <category>docker</category>
      <category>aws</category>
      <category>cloudcomputing</category>
      <category>serverless</category>
    </item>
    <item>
      <title>Temperature Sensor API in Javascript</title>
      <dc:creator>Paritosh Gupta</dc:creator>
      <pubDate>Fri, 03 Mar 2023 06:45:46 +0000</pubDate>
      <link>https://dev.to/paritoshg/temperature-sensor-api-in-javascript-n5p</link>
      <guid>https://dev.to/paritoshg/temperature-sensor-api-in-javascript-n5p</guid>
      <description>&lt;p&gt;Temperature sensors are devices used to measure temperature in solids, liquids or gases. They are used within industrial applications and have many more commercial uses. Most of the temperature sensors monitor temperature by measuring the change in resistance of an electrical current.&lt;/p&gt;

&lt;p&gt;How can one create a temperature sensor API in JavaScript using Node.js?&lt;br&gt;
To create a temperature sensor API in JavaScript, we will need to define the routes and handlers for the different endpoints of the API.&lt;/p&gt;

&lt;p&gt;`const express = require('express');&lt;br&gt;
const app = express();&lt;/p&gt;

&lt;p&gt;// Define an array to store temperature readings&lt;br&gt;
const temperatures = [];&lt;/p&gt;

&lt;p&gt;// Define a route to get the current temperature reading&lt;br&gt;
app.get('/temperature', (req, res) =&amp;gt; {&lt;br&gt;
  // Get the latest temperature reading from the array&lt;br&gt;
  const latestTemperature = temperatures.length &amp;gt; 0 ? temperatures[temperatures.length - 1] : null;&lt;/p&gt;

&lt;p&gt;// Return the latest temperature reading as JSON&lt;br&gt;
  res.json({ temperature: latestTemperature });&lt;br&gt;
});&lt;/p&gt;

&lt;p&gt;// Define a route to add a new temperature reading&lt;br&gt;
app.post('/temperature', (req, res) =&amp;gt; {&lt;br&gt;
  // Parse the temperature value from the request body&lt;br&gt;
  const temperature = req.body.temperature;&lt;/p&gt;

&lt;p&gt;// Add the temperature value to the array&lt;br&gt;
  temperatures.push(temperature);&lt;/p&gt;

&lt;p&gt;// Return a success message as JSON&lt;br&gt;
  res.json({ message: 'Temperature reading added successfully' });&lt;br&gt;
});&lt;/p&gt;

&lt;p&gt;// Start the server&lt;br&gt;
const port = 3000;&lt;br&gt;
app.listen(port, () =&amp;gt; {&lt;br&gt;
  console.log(&lt;code&gt;Temperature sensor API listening on port ${port}&lt;/code&gt;);&lt;br&gt;
});`&lt;/p&gt;

&lt;p&gt;We are using the Express.js framework for building this API, and a middleware installed to parse the request body (such as the body-parser middleware).&lt;/p&gt;

&lt;p&gt;To run this code, one needs to install the express package by running npm install express. Then, one can save the code to a file called server.js and run it with the command node server.js. The server will start listening on port 3000, and requests can be made to &lt;a href="http://localhost:3000/temperature" rel="noopener noreferrer"&gt;http://localhost:3000/temperature&lt;/a&gt; to get the current temperature.&lt;/p&gt;

</description>
    </item>
    <item>
      <title>Using MQTT.JS library</title>
      <dc:creator>Paritosh Gupta</dc:creator>
      <pubDate>Thu, 02 Mar 2023 06:28:54 +0000</pubDate>
      <link>https://dev.to/paritoshg/using-mqttjs-library-1nlc</link>
      <guid>https://dev.to/paritoshg/using-mqttjs-library-1nlc</guid>
      <description>&lt;p&gt;MQTT (Message Queuing Telemetry Transport) is a lightweight publish-subscribe messaging protocol designed for use in IoT (Internet of Things) and M2M (Machine to Machine) communication. MQTT protocol is a client-server protocol, where the clients are the IoT devices, and the server is the broker that facilitates communication between the devices.&lt;/p&gt;

&lt;p&gt;Following is an example of how to create an MQTT client using the MQTT.js library in JavaScript:&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;const mqtt = require('mqtt')

// Connect to the MQTT broker
const client = mqtt.connect('mqtt://broker.agilytics.in')

// Subscribe to a topic
client.subscribe('my/topic')

// Publish a message to a topic
client.publish('my/topic', 'Hello Agilytics!')

// Handle incoming messages
client.on('message', (topic, message) =&amp;gt; {
  console.log(`Received message on topic ${topic}: ${message}`)
})

// Handle errors
client.on('error', (error) =&amp;gt; {
  console.error(`Error: ${error}`)
})

// Disconnect from the MQTT broker
client.end()
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;This code uses the mqtt library to connect to an MQTT broker, subscribe to a topic, publish a message to that topic, and handle incoming messages and errors. You'll need to replace mqtt://broker.agilytics.in with the address of your own MQTT broker.&lt;/p&gt;

</description>
    </item>
    <item>
      <title>My Flutter Learning</title>
      <dc:creator>Paritosh Gupta</dc:creator>
      <pubDate>Tue, 02 Feb 2021 03:35:54 +0000</pubDate>
      <link>https://dev.to/paritoshg/my-flutter-learning-5fji</link>
      <guid>https://dev.to/paritoshg/my-flutter-learning-5fji</guid>
      <description>&lt;p&gt;Dear Friends,&lt;br&gt;
   Wish you a very Happy New Year 2021. Wish you health and happiness.&lt;br&gt;
Do you have a dream of developing awesome Mobile App or Web App?&lt;br&gt;
Trust me Flutter is a suitable cross platform technology to fulfill your dream.&lt;br&gt;
As the start of the month of February 2021, I have embarked my Flutter Learning journey with Google 30 Days Flutter program. &lt;/p&gt;

&lt;p&gt;Here is the link for &lt;a href="https://developers.googleblog.com/2021/01/join-us-for-30daysofflutter.html" rel="noopener noreferrer"&gt;Google 30 Days Flutter program&lt;/a&gt;&lt;/p&gt;

&lt;p&gt;Flutter is Google’s open source UI toolkit for building beautiful, natively compiled applications for mobile, web, and desktop from a single codebase. It’s one of the fastest growing, most in-demand cross platform frameworks to learn and is used by freelance developers and large organizations around the world. Flutter uses the Dart language, so it will feel natural to many of you familiar with object-oriented languages. (Ref. Google 30  Days Flutter)&lt;/p&gt;

&lt;p&gt;I am pretty excited to learn Flutter and do my ultimate activity i.e. to develop.&lt;/p&gt;

&lt;p&gt;I will keep posting about my experience while learning.&lt;/p&gt;

&lt;p&gt;Let's Join.&lt;/p&gt;

</description>
      <category>flutter</category>
      <category>webdev</category>
    </item>
  </channel>
</rss>
