Theo's Typesafe CultTTC
Theo's Typesafe Cult4y ago
98 replies
venego

is this way of handling react states a bad idea?

This is a very long ass question, it might not be worth your time anyways. so sorry in advance.

I'm a noob at react, I just know the basics and started making a relatively medium project. then as my component started having more children and grand children, I startup feeling the pain of managing all of those relationships.

So I tried useContext but it feels like the syntax is too much, and I didn't feel like I need a state manager like Redux YET for my simple project, so I made this simple snippet, and my code looks so clean. and works like a charm.

this will hold a reference to the state and the setState function, so you can use it from another component.
// each item in bridges has the states of a certain component
const Bridges = {};
// this gets called from the child component to change the state of the parent
const setState = (componentID, stateName, newState) =>  newState ?? Bridges[componentID][stateName].render(newState);
// this gets called from the child to read the state of the parent
const getState = (componentID, stateName) => Bridges[componentID][stateName].state;
// this gets called from the parent, the component you wanna share it's state with the child or re-render if the child received a delete event for example.
const initBridge = (componentID, states) => {
    if (!bridgesObj?.render) {
        bridgesObj.render = () => {
            console.error('render function is not set');
        };
    }
    // adds the parent states to the collection/store
    Bridges[componentID] = {...states};
};

export const Bridge = {initBridge, getState, setState};

I noticed that this might be similar to what's inside of react, so I consider it as bloatware, but I think it's way easier to manage than using useContext.
Was this page helpful?