I used to declare state in App.jsx which is the root component. But I wonder if it’s okay to declare it in sub-components too.
For example, let’s say there are 5 components and the structure is like below.
App > Home > Section1, Section2 > Button
And I wanna display the data in Button of each Section
Now is it okay to declare state in Home component instead of App? Which is recommended?
- Edit) I know it works good in both cases but I wanna know what’s common.
>Solution :
You can declare a state variable anywhere in the component tree. In fact, deciding where the state should live is the corner stone of React Development, so congrats you’re on the right path!
Generally speaking, you’d place the state at the closest common ancestor to all the child component that consumes it through props. Because :
- You want all your components that share the same logical information to share the same state variable. That’s what react is about, a single source of truth.
- You want your state to live as close as possible to your components to avoid prop drilling
Of course this is very generic advice, and a ton of factors can influence this decision. A good starting point would be to read This article from React’s doc on lifting the state up. It goes through the process of deciding where the state should live step by step on a concrete use case.