Home > Software engineering >  React: Setting and updating based on props
React: Setting and updating based on props

Time:09-21

Currently I am facing the problem that I want to change a state of a child component in React as soon as a prop is initialized or changed with a certain value. If I solve this with a simple if-query, then of course I get an infinite loop, since the components are then rendered over and over again.

Component (parent):

function App() {
    const [activeSlide, setActiveSlide] = useState(0);

    function changeSlide(index) {
        setActiveSlide(index);
    }

    return (
        <div className="app">
            <div className="app__nav">
                <Button icon="FiSun" handler={changeSlide} active={activeSlide} index="0" />
                <Button icon="FiSettings" handler={changeSlide} active={activeSlide} index="1" />
            </div>
        </div>
    );
}

Component (child):

function Button(props) {
    const Icon = Icons[props.icon];
    const [activeClass, setActiveClass] = useState("");

    // This attempts an endless loop
    if(props.active == props.index) {
        setActiveClass("active");
    }

    function toggleView(e) {
        e.preventDefault();
        props.handler(props.index);
    }

    return(
        <button className={activeClass} data-index={props.index} onClick={toggleView}>
            <Icon />
        </button>
    )
}

Is there a sensible and simple approach here? My idea would be to write the if-query into the return() and thus generate two different outputs, even though I would actually like to avoid this

CodePudding user response:

The React docs have a nice checklist here used to determine if something does or does not belong in state. Here is the list:

  1. Is it passed in from a parent via props? If so, it probably isn’t state.
  2. Does it remain unchanged over time? If so, it probably isn’t state.
  3. Can you compute it based on any other state or props in your component? If so, it isn’t state.

The active class does not meet that criteria and should instead be computed when needed instead of put in state.

return(
  <button className={props.active == props.index ? 'active' : ''} data-index={props.index} onClick={toggleView}>
    <Icon />
  </button>
)

CodePudding user response:

This is a great use of useEffect.

instead of the if statement you can replace that with;

const {active, index} = props

useEffect(_ => {
    if(active == index) {
        setActiveClass("active");
    }
 }, [active])

The last item in the function is a dependency, so useEffect will only run if the active prop has changed.

CodePudding user response:

Try to use the hook useEffect to prevent the infinite loop. (https://fr.reactjs.org/docs/hooks-effect.html)

Or useCallback hook. (https://fr.reactjs.org/docs/hooks-reference.html#usecallback)

Try this and tell me if it's right for you :

function App() {
    const [activeSlide, setActiveSlide] = useState(0);

    const changeSlide = useCallback(() => {
        setActiveSlide(index);
    }, [index]);

    return (
        <div className="app">
            <div className="app__nav">
                <Button icon="FiSun" handler={changeSlide} active={activeSlide} index="0" />
                <Button icon="FiSettings" handler={changeSlide} active={activeSlide} index="1" />
            </div>
        </div>
    );
}

CodePudding user response:

React automatically re-renders a component when there is a change in the state or props. If you're just using activeClass to manage the className, you can move the condition in the className as like this and get rid of the state.

<button className={props.active === props.index ? 'active' : ''} data-index={props.index} onClick={toggleView}>
  <Icon />
</button>

however, if you still want to use state in the child component, you can use the useEffect hook to to update the state in the child component.

  • Related