Nikunj Shah

Nikunj Shah

1573456188

8 Useful React Tricks that Every React Developer Should Know

React has gone through many shifts in stages that never fail to amaze its fans.

This article will go over eight neat tricks in React that every React developer should know.

Now, I’m not expecting every single item in this list to be new to you, but I’m hoping that you find at least one item in this list useful to you that you didn’t know you could do until now.

Here are eight tricks in React you should know:

1. Create React Elements With Strings

The first item on this list will go over creating a regular react DOM element with simple strings that represent an HTML DOM element tag. More precisely, a string that represents a DOM element.

For example, you can create React components by assigning the string 'div' to a variable, like so:

import React from 'react'

const MyComponent = 'div'

function App() {
  return (
    <div>
      <h1>Hello</h1>
      <hr />
      <MyComponent>
        <h3>I am inside a {'<div />'} element</h3>
      </MyComponent>
    </div>
  )
}

React will just call React.createElement and use that string to create the element internally. Isn’t that neat?

Used commonly in component libraries like Material UI, you can declare a component prop for which the caller can decide the root node of the component to become the value of props.component, like so:

function MyComponent({ component: Component = 'div', name, age, email }) {
  
  return (
    <Component>
      <h1>Hi {name}</h1>
      <div>
        <h6>You are {age} years old</h6>
        <small>Your email is {email}</small>
      </div>
    </Component>
  )
}

This is how you can use it:

function App() {
  return (
    <div>
      <MyComponent component="div" name="George" age={16} email="george@gmail.com">
    </div>
  )
}

You can also pass in your custom component where that will be used as the root node:

function Dashboard({ children }) {
  return (
    <div style={{ padding: '25px 12px' }}>
      {children}
    </div>
  )
}

function App() {
  return (
    <div>
      <MyComponent component={Dashboard} name="George" age={16} email="george@gmail.com">
    </div>
  )
}

2. Use Error Boundaries

In JavaScript, we are used to handling most errors inside the execution of code with try/catch, the block of code that can “catch” errors that occur. When these errors are caught in the catch block, you can save your application from crashing within code boundaries.

An example of this would look something like this:

function getFromLocalStorage(key, value) {
  try {
    const data = window.localStorage.get(key)
    return JSON.parse(data)
  } catch (error) {
    console.error
  }
}

React is ultimately just JavaScript, so we may assume that we can catch and handle errors using the same strategy. However, due to the nature of React, JavaScript errors inside components corrupt React’s internal state and cause it to emit cryptic errors on future renders.

For this reason, the React team introduced error boundaries, and every React developer should know about them so they can use them in their React apps.

The problem with errors happening prior to error boundaries was that when these cryptic errors were emitted in future renders, after happening in previous renders, React did not provide a way to handle nor recover from them in components. This is why we all need error boundaries!

Error boundaries are React components that catch errors anywhere in the component tree, log them, and can display a fallback UI instead of the component tree that crashed.

They catch errors during rendering, inside lifecycle methods, and inside the constructors of the entire tree below them (which is the reason why we declare and render them at the top of our app somewhere).

Here is an example from the React documentation:

class ErrorBoundary extends React.Component {
  constructor(props) {
    super(props)
    this.state = { hasError: false }
  }
  
  static getDerivedStateFromError(error) {
    // Update state so the next render will show the fallback UI.
    return { hasError: true }
  }
  
  componentDidCatch(error, errorInfo) {
    // You can also log the error to an error reporting service
    logErrorToMyService(error, errorInfo)
  }
  
  render() {
    if (this.state.hasError) {
      // You can render any custom fallback UI
      return <h1>Something went wrong.</h1>
    }
    return this.props.children
  }
}

Then you can use it as a regular component:

<ErrorBoundary>
  <MyWidget />
</ErrorBoundary>

3. Retain Previous Values

While updating props or state, you can retain their previous values just by using React.useRef.

For example, to track the current and previous changes of an array of items, you can create a React.useRef which gets assigned the previous value and a React.useState for the current value:

function MyComponent() {
  const [names, setNames] = React.useState(['bob'])
  const prevNamesRef = React.useRef([])
  
  React.useEffect(() => {
    prevNamesRef.current = names
  })
  
  const prevNames = prevNamesRef.current
  
  return (
    <div>
      <h4>Current names:</h4>
      <ul>
        {names.map((name) => (
          <li key={name}>{name}</li>
        ))}
      </ul>
      <h4>Previous names:</h4>
      <ul>
        {prevNames.map((prevName) => (
          <li key={prevName}>{prevName}</li>
        ))}
      </ul>
    </div>
  )
}

This works because React.useEffect is run after the components have finished rendering.

When setNames is called, the component re-renders and prefNamesRef will hold the previous names because React.useEffect is the last code executed from the previous render.

And, since we re-assigned prevNamesRef.current in the useEffect, it becomes the previous names in the next render phase because it was last assigned the names from the previous render phase.

4. Use React.useRef for Flexible Non-Stale Value Checks

Before React Hooks were introduced in React, we had the componentDidMount static method of class components if we wanted to ensure operations, like fetching data, happened after the component mounted on the DOM.

When React Hooks came out, it quickly became the most popular way to write our components as opposed to using class components. When we wanted to track if a component has mounted to prevent setting the state after the component unmounts, we would do something like this:

import React from 'react'
import axios from 'axios'

class MyComponent extends React.Component {
  mounted = false
  
  state = {
    frogs: [],
    error: null,
  }
  
  componentDidMount() {
    this.mounted = true
  }
  
  componentWillUnmount() {
    this.mounted = false
  }
  
  async fetchFrogs = (params) => {
    try {
      const response = await axios.get('https://some-frogs-api.com/v1/', { params })
      if (this.mounted) {
        this.setState({ frogs: response.data.items })
      }
    } catch (error) {
      if (this.mounted) {
        this.setState({ error })
      }
    }
  }
  
  render() {
    return <div>
    <h4>Frogs:</h4>
    <ul>
    {this.state.frogs.map((frog) => <li key={frog.name}>{frog.name}</li>)}
    </ul>
    </div>
  }
}

Hooks did not have a componentDidMount after migrating to React Hooks and the concept of memory leaks from state updates occurring after unmounting still applies with Hooks.

However, a similar way to componentDidMount using React Hooks is to use React.useEffect since it is executed after components are finished rendering. If you use React.useRef to assign the value of the mounted value here, you can achieve the same effect as the class component example:

import React from 'react'
import axios from 'axios'

function MyComponent() {
  const [frogs, setFrogs] = React.useState([])
  const [error, setError] = React.useState(null)
  const mounted = React.useRef(false)
  
  async function fetchFrogs(params) {
    try {
      const response = await axios.get('https://some-frogs-api.com/v1/', {
        params,
      })
      if (mounted.current) {
        setFrogs(response.data.items)
      }
    } catch (error) {
      if (mounted.current) {
        setError(error)
      }
    }
  }
  
  React.useEffect(() => {
    mounted.current = true
    return function cleanup() {
      mounted.current = false
    }
  }, [])
  
  return (
    <div>
      <h4>Frogs:</h4>
      <ul>
        {this.state.frogs.map((frog) => (
          <li key={frog.name}>{frog.name}</li>
        ))}
      </ul>
    </div>
  )
}

Another example of a good use case to keep track of latest changes without causing re-renders is to use it in conjunction with React.useMemo like this (source):

function setRef(ref, value) {
  // Using function callback version
  if (typeof ref === 'function') {
    ref(value)
    // Using the React.useRef() version
  } else if (ref) {
    ref.current = value
  }
}

function useForkRef(refA, refB) {
  return React.useMemo(() => {
    if (refA == null && refB == null) {
      return null
    }
    return (refValue) => {
      setRef(refA, refValue)
      setRef(refB, refValue)
    }
  }, [refA, refB])
}

This will create a new function if the ref props change and are defined. This means that React will call the old forked ref with null, and the new forked ref with the current ref.

And since React.useMemo is used, the refs will be memoized until ref props of refA or refB change, in which natural cleanup occurs from this behavior.

5. Use React.useRef for Customizing Elements That Depend on Other Elements

React.useRef has several useful use cases including assigning itself to the ref prop to React nodes:

function MyComponent() {
  const [position, setPosition] = React.useState({ x: 0, y: 0 })
  const nodeRef = React.useRef()
  
  React.useEffect(() => {
    const pos = nodeRef.current.getBoundingClientRect()
    setPosition({
      x: pos.x,
      y: pos.y,
    })
  }, [])
  
  return (
    <div ref={nodeRef}>
      <h2>Hello</h2>
    </div>
  )
}

If we wanted to grab the position of the div element’s coordinates, this example is sufficient.

However, if another element somewhere in the app wants to update their own positions the same time position changes or applies some condition logic accordingly, the best way to do it is using the ref callback function pattern.

When using the callback function pattern, you will receive either the React component instance or the HTML DOM element as the first argument.

The example below just shows a simple example where setRef is the callback function being applied to a ref prop. You can see that, inside setRef, you have the ability to do whatever you need as opposed to directly applying the React.useRef version to the DOM element:

const SomeComponent = function({ nodeRef }) {
  const ownRef = React.useRef()
  
  function setRef(e) {
    if (e && nodeRef.current) {
      const codeElementBounds = nodeRef.current.getBoundingClientRect()
      // Log the <pre> element's position + size
      console.log(`Code element's bounds: ${JSON.stringify(codeElementBounds)}`)
      ownRef.current = e
    }
  }
  
  return (
    <div
      ref={setRef}
      style={{ width: '100%', height: 100, background: 'green' }}
    />
  )
}

function App() {
  const [items, setItems] = React.useState([])
  const nodeRef = React.useRef()
  
  const addItems = React.useCallback(() => {
    const itemNum = items.length
    setItems((prevItems) => [
      ...prevItems,
      {
        [`item${itemNum}`]: `I am item # ${itemNum}'`,
      },
    ])
  }, [items, setItems])
  
  return (
    <div style={{ border: '1px solid teal', width: 500, margin: 'auto' }}>
      <button type="button" onClick={addItems}>
        Add Item
      </button>
      <SomeComponent nodeRef={nodeRef} />
      <div ref={nodeRef}>
        <pre>
          <code>{JSON.stringify(items, null, 2)}</code>
        </pre>
      </div>
    </div>
  )
}

6. Higher-Order Components

A common pattern in plain JavaScript to create powerful reusable functions is the higher-order function. Since React is ultimately JavaScript, you can also use higher-order functions inside React.

For reusable components, the trick is to use higher-order components.

A higher-order component is when you have a function that takes a component as an argument and returns a component.

Just like how higher-order functions can be employed to abstract away logic and be shared amongst other functions in the app, higher-order components enable us to abstract away logic from components and share them amongst other components.

This means that you can employ a bunch of reusable components to reuse across your application.

Here is an example of a higher-order component. In this snippet, a higher-order component withBorder takes in a custom component and returns a hidden “middle layer” component.

Then, when the parent decides to render this higher-order component that was returned, it is called as a component and receives the props that were passed in from the “middle layer component”:

import React from 'react'

// Higher order component
const withBorder = (Component, customStyle) => {
  class WithBorder extends React.Component {
    render() {
      const style = {
        border: this.props.customStyle ? this.props.customStyle.border : '3px solid teal'
      }
      return <Component style={style} {...this.props} />
    }
  }
  
  return WithBorder
}

function MyComponent({ style, ...rest }) {
  return (
    <div style={style} {...rest}>
        <h2>
          This is my component and I am expecting some styles.
        </h2>
    </div>
  )
}

export default withBorder(MyComponent, {
  border: '4px solid teal'
})

7. Render Props

One of my favorite tricks to use in the React library is the render prop pattern. It is similar to higher-order components in a way that it solves a similar problem: sharing code between multiple components.

Render props expose a function who’s purpose is to pass back everything the outside world needs to render its children.

The most basic way to render components in React is to render them like so:

function MyComponent() {
  return <p>My component</p>
}

function App() {
  const [fetching, setFetching] = React.useState(false)
  const [fetched, setFetched] = React.useState(false)
  const [fetchError, setFetchError] = React.useState(null)
  const [frogs, setFrogs] = React.useState([])
  
  React.useEffect(() => {
    setFetching(true)
    
    api.fetchFrogs({ limit: 1000 })
      .then((result) => {
        setFrogs(result.data.items)
        setFetched(true)
        setFetching(false)
      })
      .catch((error) => {
        setError(error)
        setFetching(false)
      })
      
  }, [])
  
  return <MyComponent fetching={fetching} fetched={fetched} fetchError={fetchError} frogs={frogs} />
}

With render props, the prop that renders its children is by convention called render, like so:

function MyComponent({ render }) {
  const [fetching, setFetching] = React.useState(false)
  const [fetched, setFetched] = React.useState(false)
  const [fetchError, setFetchError] = React.useState(null)
  const [frogs, setFrogs] = React.useState([])
  
  React.useEffect(() => {
    setFetching(true)
    
    api.fetchFrogs({ limit: 1000 })
      .then((result) => {
        setFrogs(result.data.items)
        setFetched(true)
        setFetching(false)
      })
      .catch((error) => {
        setError(error)
        setFetching(false)
      })
  }, [])
  
  return render({
    fetching,
    fetched,
    fetchError,
    frogs,
  })
}

In the example, MyComponent is an example of a component we refer to as the render prop component, because it expects render as a prop and calls it to render its children.

This is a powerful pattern in React as we’re allowed to pass in shared state and data through the render callback as arguments, allowing the component to be rendered and reused in multiple components:

function App() {
  return (
    <MyComponent
      render={({
        fetching,
        fetched,
        fetchError,
        frogs
      }) => (
        <div>
          {fetching ? 'Fetching frogs...' : fetched ? 'The frogs have been fetched!' : fetchError ? `An error occurred while fetching the list of frogs: ${fetchError.message}` : null}
          <hr />
          <ul style={{
            padding: 12,
          }}>
            {frogs.map((frog) => (
              <li key={frog.name}>
                <div>
                Frog's name: {frog.name}
                </div>
                <div>
                  Frog's age: {frog.age}
                </div>
                <div>
                  Frog's gender: {frog.gender}
                </div>
              </li>
            ))}
          </ul>
        </div>
      )}
    />
  )
}

8. Memoize

One of the most important things to know as a React developer is optimizing performance from your components like React.memo. This can help prevent nasty errors like infinite loops that cause a catastrophic crash while the app is running.

Read about some of the several ways you can apply memoization in your React app below:

Conclusion

And that concludes this post! I hope you found this to be valuable and look out for more in the future.

#React #web-development #javascript

What is GEEK

Buddha Community

8 Useful React Tricks that Every React Developer Should Know
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

Aria Barnes

Aria Barnes

1627031571

React 18: Things You Need To Know About React JS Latest Version

The most awaited version of React 18 is finally out now. Its team has finally revealed the alpha version of React 18 and its plan, though the official launch is still pending. This time the team has tried something and released the plan first to know their user feedback because the last version of React 17 was not that much appreciated among developers.

According to Front-end Frameworks SurveyReact JS has ranked top in the list of most loved frameworks. Thus, the developer communities expect a bit higher from the framework, so they are less appreciative of the previous launch.
ReactJS stats.pngSo, this time React 18 will be a blast. For beginners, the team is working on a new approach. They have called a panel of experts, library authors, educators, and developers to take part in a working group. Initially, it will be a small group.

I am not a part of this release but following the team on their GitHub discussion group. After gathering the information from there, I can say that they have planned much better this time.

React 17 was not able to meet the developer's community. The focus was all primarily centered on making it easier to upgrade React itself. React 18 release will be the opposite. It has a lot of features for react developers.

Read more here: React 18: Things You Need To Know About React JS Latest Version

#hire react js developers #hire react js developers india #react developers india #react js developer #react developer #hire react developers

sophia tondon

sophia tondon

1621250665

Top React JS Development Company | React JS Development Services

Looking to hire dedicated top Reactjs developers at affordable prices? Our 5+ years of average experienced Reactjs developers comprise proficiency in delivering the most complex and challenging web apps.

Hire ReactJS developers online on a monthly, hourly, or full-time basis who are highly skilled & efficient in implementing new technologies and turn into business-driven applications while saving your cost up to 60%.

Planning to** outsource React web Development services from India** using Reactjs? Or would you like to hire a team of Reactjs developers? Get in touch for a free quote!

#hire react js developer #react.js developer #react.js developers #hire reactjs development company #react js development india #react js developer

sophia tondon

sophia tondon

1625803880

Top React JS Development Company | React JS Development Services

Looking to hire top Reactjs developers at affordable prices? Our 5+ years of average experienced Reactjs developers comprise proficiency in delivering the most complex and challenging web apps.

Hire ReactJS developers online on a monthly, hourly, or full-time basis who are highly skilled & efficient in implementing new technologies and turn into business-driven applications while saving your cost up to 60%.

Planning to outsource React Js web Development services using Reactjs? Or would you like to hire a team of Reactjs developers? Get in touch for a free quote!

#hire react js developers #hire reactjs developers #hire react js developer #hire react.js developer #hire react.js developers #hire react developer

sophia tondon

sophia tondon

1620378787

Why And Where To Use ReactJS For Web Development?

There are numerous frameworks and libraries accessible in this advanced digital world that can help you with agile web development. But among all, only a few offer excellent performance and possess robust features and functionalities. ReactJS is one of the most famous web frameworks these days, usually used in web development.

Read More - https://medium.com/predict/why-and-where-to-use-reactjs-for-web-development-fb6c53231474

##react js development company #hire react developer #react js developers #react developers for hire #react.js developers #reactjs development services