I’m trying to refactor a component that receives a lot of properties. I am trying to think on how to improve for example with patterns such as these https://javascript.plainenglish.io/5-advanced-react-patterns-a6b7624267a6
But how would you simplify the properties in a code like this one
const App = () => {
const [ab, setAb] = useState();
const [c, setC] = useState();
const [d, setD] = useState();
// stuff with all available state
return (<Example ab={ab} setAb={setAb} c={c} setC={setC} d={d} setD={setD} />)
}
const Example = ({ab, setAb}) => {
const [a, setA] = useState();
// stuff with all available vars
return (
<>
<A ab={ab} setAb={setAb} a={a} setA={setA}/>
<B ab={ab} setAb={setAb}/>
<C c={c} setC={setC} d={d} setD={setD}/>
</>
)
}
const A = ({ab, setAb, a, setA}) => {
// stuff with all available vars
return <div>{a}</div>
}
const B = ({ab, setAb}) => {
// stuff with setAb
return <div>{ab}</div>
}
const C = ({c, setC, d, setD}) => {
// stuff with all available vars
return (<D d={d} setD={setD} />)
}
const D = ({d, setD}) => {
// stuff with setAb
return (<div>{d}</div>);
}
I would like to reduce the number of props, or group them. Is there any pattern of grouping those that go together? (state + state modifier)
2
Answers
This sounds like a job for either Redux or Context Providers. If you find yourself passing props down multiple levels of components, you are doing something called "Prop drilling" which is an anti-pattern. Refactoring your components to use something like a Context Provider allows you to hold your state in a top-level Context Provider component and then access the state of the Provider using a useContext hook.
Or, if you are dealing with large volumes of asynchronous data, you may prefer to use a tool like Redux or Zustang which uses Reducers to handle state. Both approaches have their benefits and drawbacks with ContextProviders being the easiest to learn, however, Redux/Zustang have the best scalability and performance (only at an incredibly large scale though, React Context holds up just fine for most applications)
Learn Redux – https://redux.js.org/introduction/learning-resources
OR
Learn React Context – https://react.dev/learn/passing-data-deeply-with-context
Zustand is an excellent option that works very well even when you want to use Server components and don’t want to have a wrapper component just to create the providers.