What is causing the discrepancy in state/CSS transition times for this basic ReactJS slider?

If you're interested, I made a functional demo sandbox which can be found here

This particular demo showcases a basic array cycler with 3 elements that are displayed as slides moving left or right depending on the selected direction.

While I acknowledge that my approach may not be optimal, I am open to any suggestions for improvement.

The main issue I encountered was ensuring that the sliding functionality worked smoothly in both directions. This required me to incorporate a delay when transitioning the slide to the left. Additionally, I admit that my naming convention may be confusing as the button actions (prev/next) do not align directly with the cycling/sliding behavior.

In summary, the key component of this demo is the onClick handler for the prev/next buttons, passing a boolean value for direction and utilizing CSS animations for motion effects. While I am aware that nested ternaries are generally discouraged, they were necessary for this specific implementation.

const cycleArr = cyclePrev => {
    if (!slideDone) {
      return;
    }
    setSlideDone(false);
    const newArrSort = cyclePrev ? cycleLeft(slides) : cycleRight(slides);
    slideClassRef.current.classList = slideDir
      ? `App ${slideDir === "left" ? "slide-left" : "slide-right"}`
      : "App";
    if (slideDir === "left") {
      setSlides(newArrSort);
      setTimeout(() => {
        slideClassRef.current.classList = "App";
        setSlideDone(true);
      }, 1050);
    } else {
      setTimeout(() => {
        slideClassRef.current.classList = "App";
        setSlides(newArrSort);
        setSlideDone(true);
      }, 1000);
    }
  };

Although I could have used an existing solution like slick carousel, I opted to create this demo to highlight my challenges with state management in ReactJS. My goal is to improve and refine my approach in handling complex state scenarios.

Answer №1

Your query seems a bit unclear to me, but if you're talking about the slight delay of 50ms when sliding, my assumption is that the invocation of setSlides(newArrSort); not only updates the state but also triggers an immediate re-render in React, causing a delay that doesn't sync well with the CSS transition.

Avoiding anti-patterns isn't meant to complicate things for you; it's there to prevent you from falling into a messy situation :)

Components may re-render whenever React sees fit, which is why it's important to store state properly and handle effects elegantly in useEffect hooks. I suggest following a more React-oriented data flow, where changes are made at the top level of state and allowed to cascade down, adjusting to the updated state and applying appropriate CSS styles. It's declarative, much like HTML and CSS. Instead of telling the browser what to paint, you describe how it should be painted.

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

Tips for reducing text in a card design

As a newcomer to codeigniter 4, I recently created an event card with a lengthy description. However, when I attempted to display the event data from the database on the card, it ended up becoming elongated due to the length of the description: https://i. ...

Exploring the benefits of refactoring jQuery promises in use cases

I've been thinking about how to optimize this pseudo-code: function foo() { if (condition) { return somethingReturningPromise().then(function (data) { doSomethingOnSuccess(data); return mainFunctionReturningPromise(); // he ...

Modifying vertices in THREE.LineSegment: Adding and deleting

I am facing an issue with a THREE.LineSegments object, where I need to dynamically change the number of vertices. However, when I try to modify the geometry vertices array, the lines with removed vertices remain in place. Is there a way to remove vertices ...

The issue of calling the child window function from the parent window upon clicking does not seem to be functioning properly on Safari and Chrome

I'm attempting to invoke the function of a child window from the parent window when a click event occurs. Strangely, this code works in Firefox but not in Safari or Chrome. Here is the code snippet I am using: var iframeElem = document.getElementById( ...

AngularJS: Recommendations for structuring code to dynamically update the DOM in response to AJAX requests

Within Angular's documentation, there is a straightforward example provided on their website: function PhoneListCtrl($scope, $http) { $http.get('phones/phones.json').success(function(data) { $scope.phones = data; }); $scope.order ...

React's useState hook fails to correctly update object values

Having an issue with updating a state variable with an object in React. The code is as follows: async function getServers() { console.log("ready") const response = await fetch('http://localhost:3000/server/servers').th ...

Failure of Websocket on OpenShift platform with NodeJS

Although several similar questions have been raised here before, none of the suggested solutions appear to be effective. (Relevant responses will be shared below) I am facing an issue with running a basic websocket app on openshift. The application runs f ...

When you click on a list of links, a stylish image gallery will appear using fancybox

Can anyone lend a hand with this? I would greatly appreciate any assistance CSS <a id="fancybox" href="javascript:;">Gallery 1</a> <br /> <a id="fancybox" href="javascript:;">Gallery 2</a> <br /> <a id="fancybox" hr ...

The JavaScript code is not running as expected!

i have this index.html file: <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd"> <html xmlns="http://www.w3.org/1999/xhtml"> <head> <meta http-equiv="Content-Type" ...

Guide to dynamically updating the href of an SVG Image in Angular HTML

I am currently iterating through a list of employee objects, each containing an image URL that I need to incorporate into an SVG - Image element. <div *ngFor ="emp of employees"> <defs> <pattern id = "attachedImage" height ...

CSS Flexbox - Choose all elements that appear at the start of a new line (Wrap)

Is there a CSS selector that can prevent content insertion on new lines when using the wrap feature in CSS-Flexbox? I am utilizing CSS-Flexbox for a layout with the wrap option, but I do not know the number of lines beforehand. I need a solution where the ...

Error in Typescript: Function not being triggered on button click

As someone who is just starting out with typescript, I've been tackling a simple code that should display an alert message in the browser when a button is clicked. I've experimented with the button and input tags, as well as using both onclick ev ...

What steps can I take to restrict a draggable element to the body, prevent text selection, and allow form inputs to be enabled?

I'm currently utilizing the react-draggable library for my project. In order to ensure that the element remains within the confines of the body element, prevent text selection, and allow interaction with form inputs inside the draggable element, I en ...

Incorporating specialized pseudo CSS styling to a class

Having a bit of a tricky situation here, I am dealing with the following class: <li><a href="test.html" class="hvr-overline-from-left">Test</a></li> Here is the corresponding CSS: .hvr-overline-from-left { display: inline-block ...

attempting to access a variable which was initialized within a function in different sections of the code base

My goal is to retrieve a variable created within a function that is nested in a resize event parameter in jQuery. This variable should be dynamically updated each time the user resizes the browser window. I intend to utilize this variable to set the width ...

How to customize the background color of a hyperlink in an HTML email using Outlook 2010

The background color (shown in red) is currently only applying to the text within this link, rather than the entire link. Additionally, there is padding present on the link. This specific issue pertains to Outlook 2010. If anyone has insight on how to e ...

How can I upload an image file using VueJS and Django Rest Framework?

Hello, I am currently in the process of editing a blog page using VueJS and Django Rest Framework. However, I am facing an issue when trying to upload a photo - I keep receiving an error message stating that "the sent data is not a file." Additionally, I a ...

Javascript updating text according to input in textbox functions properly initially, but the changes disappear afterward

This solution functions correctly for a brief moment before disappearing. function checkTFW() { var TFW = document.getElementById("TFW").value if (TFW == "mexicans") { document.getElementById("image").innerHTML = "<h1>Success!</h1>"; ...

Difficulty arises when attempting to render a Vue component after splitting it into a new component

I previously had a Vuetify dialog setup in my location view to delete a location from a list. Now, I have a second list for Users that requires the same functionality and dialog. This seemed like a good opportunity to refactor and move my delete dialog int ...

Unable to activate click function in Jquery

Here is a basic HTML page snippet: <html> <head> <script src="http://code.jquery.com/jquery-latest.min.js" type="text/javascript"> </script> <script> $(document).ready(function () { $('#test').click(); }); < ...