jeudi 21 mars 2019

React hooks: activable states patterns

I'm trying to create a component that can activate/disable some functionality depending on the props. All of those functions will need a state that has to be managed.

I was trying to think to a possible pattern that would permit us not to create the state in case the connected functionality is not active. I thought to 2 possible way to do that:

WAY #1

function useFunctionality(initState, enable) {
    if (!enable) {
        return null;
    }

    const [funct, updateFunct] = useState(init);
    return funct;
}

function Component({ enableFunct }) {
    const funct = useFunctionality('test', enableFunct);
    return (...);
}

WAY #2

function useFunctionality(initState, enable) {
    const [funct, updateFunct] = useState(init);
    return enable ? funct : null;
}

function Component({ enableFunct }) {
    const funct = useFunctionality('test', enableFunct);
    return (...);
}

In both ways, hooks keep working. The question is: which way do you feel more correct? There is a better way to do this?

Aucun commentaire:

Enregistrer un commentaire