Today I learned how to fix a weird behavior in React Slick when infinite is set to false and initialSlide > 1.

In our project, I noticed something off — when the slider wasn’t infinite and started from, say, slide 2 or 3, it didn’t render correctly. The wrong slide appeared, and the internal position seemed out of sync.

After some digging, I found an GitHub issue confirming this bug. The fix? Manually trigger slickGoTo() once on mount.

Changing slide works incorrect when infinite is false and initialSlide > 1 · Issue #1946 · akiran/react-slick
Changing slide when initialSlide > 1 and infinite is false works wrong. When I swipe right I expect to see next slide(initial + 1), but I always see second slide as next, when I swipe left, I alway…

Here’s the TypeScript version of the workaround I ended up using:

import * as React from 'react';
import {default as SlickSlider} from 'react-slick';

interface Props extends React.ComponentProps<typeof SlickSlider> {
  ref?: React.MutableRefObject<SlickSlider | null>;
}

const Slider = (props: Props) => {
  const {initialSlide} = props;
  const fallbackSliderRef = React.useRef<SlickSlider | null>(null);
  const sliderRef = props.ref || fallbackSliderRef;

  const hasSetPosition = React.useRef<boolean>(false);

  /**
   * workaround for issue changing slide works incorrect when infinite is false and initialSlide > 1
   * https://github.com/akiran/react-slick/issues/1946#issuecomment-768935762
   */
  React.useEffect(() => {
    if (
      sliderRef.current &&
      !hasSetPosition.current &&
      typeof initialSlide === 'number'
    ) {
      sliderRef.current.slickGoTo(initialSlide);
      hasSetPosition.current = true;
    }
    // run on first render only
    // eslint-disable-next-line react-hooks/exhaustive-deps
  }, []);

  return <SlickSlider {...props} ref={sliderRef} />;
};

export default React.memo(Slider);

It’s a small fix, but it makes a big difference.
Sometimes “knowing where to poke” is half the battle when dealing with third-party components.

React slick typescript workaround for issue changing slide works incorrect when infinite is false and initialSlide > 1
React slick typescript workaround for issue changing slide works incorrect when infinite is false and initialSlide > 1 - SlickSlider.tsx

#TIL - `React Slick` + `TypeScript` Workaround for Changing Slide Bug

TIL how to fix React Slick’s Changing Slide bug when infinite is false — by calling slickGoTo() once after mount.