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 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 Set State Inside a React useEffect Hook Callback?

Sometimes, we want to set states inside the React useEffect hook callback.

In this article, we’ll look at how to set states inside the React useEffect hook callback.

Set State Inside a useEffect Hook

We can set state inside the useEffect hook by merging the values of the existing state with the new values and returning that as the state in the state updater function.

For instance, we write:

useEffect(() => {
  setState(state => ({ ...state, foo: props.foo }));
}, [props.foo]);

useEffect(() => {
  setState(state => ({ ...state, bar: props.bar }));
}, [props.bar]);

We watch the props properties by passing them into the array.

Then we merge the items into the state object that we return in the callback.

Conclusion

We can set state inside the useEffect hook by merging the values of the existing state with the new values and returning that as the state in the state updater function.

Categories
React Answers

How to Set Body Styles with React?

Sometimes, we want to set body styles within our React app.

In this article, we’ll look at how to set body styles within our React app.

Set Body Styles with React

Within our React component, we can set the body style with plain JavaScript.

For instance, we can write:

componentDidMount(){
  document.body.style.backgroundColor = "green";
}

componentWillUnmount(){
  document.body.style.backgroundColor = null;
}

We set the document.body.style.backgroundColor property to set the background color.

componentDidMount lets us run code when the component mounts.

componentWillUnmount runs when the component unmounts.

Conclusion

Within our React component, we can set the body style with plain JavaScript.

Categories
React Answers

How to Create a Modal in a React App?

We can use React’s portal feature to render our component anywhere.

This way, we can create a modal that’s attached to whatever element we want.

For instance, we can write:

const ModalComponent = ({ children, onClose }) => {
  return createPortal(
    <div className="modal" onClick={onClose}>
      {children}
    </div>,
    document.getElementById("portal")
  );
};

class App extends React.Component {
  constructor(props) {
    super(props);

    this.state = {
      showModal: false
    };
  }

  render() {
    return (
      <div>
        <button onClick={() => this.setState({ showModal: true })}>
          Open modal
        </button>
        {this.state.modalOpen && (
          <ModalComponent onClose={() => this.setState({ showModal: false })}>
            <h1>modal content</h1>
          </ModalComponent>
        )}
      </div>
    );
  }
}

We create a ModalComponent component to let us nest content inside it.

We can do that since it takes the children component.

All we have to do is render the children prop.

We use React’s createPortal method to let us render the div anywhere we want.

In App , we created a button to let us open the modal.

To do that, we set the showModal state to true .

We also created a function that we pass into the onClose prop of ModalComponent so that showModal can be set to false .

This will close the modal since ModalComponent is only shown when showModal is true .