Thinking In React Part -3

Hello Fellow developers welcome to final part of how to think in react.

Step 4: Identify Where our State Lives

We have identified what  minimal set of app state is. Next, we need to identify which component should mutate, or own this state.

React is about one-way data flow down  component hierarchy. It may not be clear which component should own what state. This is often most challenging part for newcomers to understand, so we will follow these steps to figure it out:

For each state in your application:

  • Identify that every component that renders something based on state.
  • Find  common owner component.
  • Either common owner or another component higher up in hierarchy should own the state.
  • If you can’t find  component where it makes sense to own a state, create a new component solely for holding a state and add it somewhere in hierarchy above the common owner component.

Let’s run through this strategy for application:

  • ProductTable needs to filter product list based on state and SearchBar needs to display search text and checked state.
  • The common owner component is FilterableProductTable.
  • It conceptually makes sense for filter text and checked value to live in FilterableProductTable

Cool, so we’ve decided that our state lives atFilterableProductTable. First, add instance property this.state = {filterText: '', inStockOnly: false} to FilterableProductTable’s constructor to reflect the initial state of our application. Then, pass filterText,  inStockOnly to ProductTable and SearchBar as  prop. Finally, use these props to filter the rows in ProductTable and set  values of form fields in SearchBar.

Step 5: Add an Inverse Data Flow

So far, we’ve built app that renders correctly as  function of props and state flowing down the hierarchy. Now it’s time to support data flowing other way:  form components deep in the hierarchy need to update the state in FilterableProductTable.

React makes this data flow explicit to help you understand how your program works, but it does require  little more typing than traditional two-way data binding.

If you try to type or check the box in previous version of the example (step 4), you’ll see that React ignores your input. This is intentional, as we’ve set value prop of input to always be equal to  state passed in from FilterableProductTable.

We want to make sure that whenever user changes the form, we update state to reflect the user input. Since component should only update their own state, FilterableProductTable will pass callback to SearchBar that will fire whenever  state should be updated. We can use onChange event on the inputs to be notified of it. Callbacks passed by FilterableProductTable will call setState(), and app will be updated.



That’s it for this blog feel free to raise questions in comment section

Submit a Comment

Your email address will not be published. Required fields are marked *


Select Categories