Categories
React Answers

How to Reduce State Updater Calls in React Function Component?

To optimize the performance of our React app, we should find ways to reduce state updater calls in React function components.

In this article, we’ll find ways to reduce state updater calls in React function components.

Reduce State Updater Calls in Function Component

To reduce state updater calls in a function component, we can use one state to store an object.

And we can use the state update function to update the object instead of using multiple state updater functions to update individual values.

For instance, we can write:

const {useState, useEffect} = React;

function App() {
  const [userRequest, setUserRequest] = useState({
    loading: false,
    user: null,
  });

  useEffect(() => {
    setUserRequest({ loading: true });
    fetch('https://randomuser.me/api/')
      .then(res => res.json())
      .then(data => {
        const [user] = data.results;
        setUserRequest({
          loading: false,
          user
        });
      });
  }, []);

  const { loading, user } = userRequest;

  return (
    <div>
      {loading && 'Loading...'}
      {user && user.name.first}
    </div>
  );
}

We have the setUserTequest function that updates a state that’s stored as an object.

It has the loading and user properties.

loading is the boolean to indicate loading.

user has the user data.

We set the loading property with setUserRequest when the useEffect callback first runs.

And in the then callback, we called our API.

And then we get the data and render it afterward.

The empty array ensures that the callback only loads when the component mounts.

Conclusion

To reduce state updater calls in a function component, we can use one state to store an object.

And we can use the state update function to update the object instead of using multiple state updater functions to update individual values

Categories
React Answers

How to Update States When Using React State Hook within setInterval

Sometimes, we want to update states when we use React state hook within setInterval.

In this article, we’ll look at how to update states when we use React state hook within setInterval.

Update States When Using React State Hook within setInterval

We can set the state within the setInterval callback to update the state when it’s run.

For instance, we can write:

const App = () => {
  const [count, setCount] = React.useState(0);

  React.useEffect(() => {
    const timer = window.setInterval(() => {
      setCount(count => count + 1)
    }, 1000);

    return () => {
      window.clearInterval(timer);
    };
  }, []);

  return (
    <div>{count}</div>
  );
}

We add the setInterval function into the useEffect callback.

We call setCount inside the callback by passing in a callback that returns the count + 1 .

count is the state that we want to set.

We return a function to clear the timer with clearInterval so that it’s cleared when the component unmounts.

The empty array will ensure that the useEffect callback is run when the component mounts.

Conclusion

We can set the state within the setInterval callback to update the state when it’s run.

Categories
React Answers

How to Add Custom HTML Attributes in JSX in a React App?

Sometimes, we want to add custom HTML attributes in our React JSX code.

In this article, we’ll look at how to add custom HTML attributes in our React JSX code.

How to Add Custom HTML Attributes in JSX

With React 16, we can add custom attributes natively.

For instance, we can write:

render() {
  return (
    <div data-foo="bar" />
  );
}

We can just add it straight into our HTML elements without doing anything special.

Use Children with React Stateless Functional Component in TypeScript

We can pass in the interface or type alias into the generic type argument of React.FunctionComponent to set the type for ur props.

As long as the alias or interface has the children prop, we can use the children prop.

For instance, we can write:

const Foo: React.FunctionComponent<FooProps> = props => (
  <div>
    <p>{props.bar}</p>
    <p>{props.children}</p>
  </div>
);

FooProps has the bar and children entries, so we can reference both in our component.

React.FC is the shorthand for React.FunctionComponent .

Before React 16.8, we use the React.StatelessComponent type instead.

For instance, we can write:

const Foo: React.StatelessComponent<{}> = props => (
  <div>{props.children}</div>
);

or:

const Foo : React.StatelessComponent<FooProps> = props => (
  <div>
    <p>{props.propInMyProps}</p>
    <p>{props.children}</p>
  </div>
);

React.SFC is the shorthand for React.StatelessComponent.

Conclusion

With React 16, we can add custom attributes natively.

Categories
React Answers

How to Disable Button with React

Sometimes, we want to disable buttons in our React app.

In this article, we’ll look at how to disable buttons in our React app.

Disable Button with React

We can disable a button with React by setting the disabled prop of the button.

For instance, we can write:

<button disabled={!this.state.value} />

We can use it in a component by writing:

class ItemForm extends React.Component {
  constructor() {
    super();
    this.state = { value: '' };
    this.onChange = this.onChange.bind(this);
    this.add = this.add.bind(this);
  }

  add() {
    this.props.addItem(this.state.value);
    this.setState({ value: '' });
  }

  onChange(e) {
    this.setState({ value: e.target.value });
  }

  render() {
    return (
      <div>
        <input
          type="text"
          value={this.state.value}
          onChange={this.onChange}
          placeholder='item name'
        />
        <button
          disabled={!this.state.value}
          onClick={this.add}
        >
          Add
        </button>
      </div>
    );
  }

We pass in the value state to let us enter the data that we want into the input field.

Then we check that in disabled prop of the button.

This way, the button is disabled if we have nothing inputted into the form field.

Conclusion

We can disable a button with React by setting the disabled prop of the button.

Categories
React Answers

How to Send Multipart Form Data with Axios in a React Component?

Sometimes, we want to send multipart form data with Axios in a React component.

In this article, we’ll look at how to send multipart form data with Axios in a React component.

Send Multipart Form Data with Axios in a React Component

We can send form data with the FormData constructor.

We can pass that straight into the Axios post method.

For instance, we can write:

import React from 'react'
import axios, { post } from 'axios';

class App extends React.Component {

  constructor(props) {
    super(props);
    this.state ={
      file:null
    }
    this.onFormSubmit = this.onFormSubmit.bind(this)
    this.onChange = this.onChange.bind(this)
    this.fileUpload = this.fileUpload.bind(this)
  }

  onFormSubmit(e){
    e.preventDefault()
    const url = 'http://example.com/upload';
    const formData = new FormData();
    formData.append('file', this.state.file);
    const config = {
      headers: {
        'content-type': 'multipart/form-data'
      }
    }
    post(url, formData, config);
      .then((response) => {
        console.log(response.data);
      })
  }

  onChange(e) {
    this.setState({ file: e.target.files[0 ]})
  }

  render() {
    return (
      <form onSubmit={this.onFormSubmit}>
        <h1>File Upload</h1>
        <input type="file" onChange={this.onChange} />
        <button type="submit">Upload</button>
      </form>
   )
  }
}

We have a file input, where we set the file input to the file that’s submitted in the onChange method.

We save the selected file object as the value of the file state.

Then when we click the Upload button, onFormSubmit is run.

In the method, we created a FomrData instance.

Then we append our file into the FormData instance.

We also set the header so that we indicate that we’re sending form data.

Once we did that, we proceed with our file upload.

Conclusion

We can send form data with the FormData constructor.

We can pass that straight into the Axios post method.