Home > Software engineering >  React: best practice for state control
React: best practice for state control

Time:08-08

Lately I've noticed that I'm writing a lot of React code were I have 2 components:

  1. Data filter
  2. Data display

In the first component I might have N possible filters to apply to the data. These filters often complex components on their own. When the user defines the filters I need to pass it from 1st component to the 2nd for display. Example: https://codesandbox.io/s/wonderful-sutherland-16zhp8?file=/src/App.js

What I see in many cases to happen is that I manage the state of the filter in multiple places. In the example above, I have it in the Toolbar component and in the parent one.

What is the best way of managing states in such case?

CodePudding user response:

You should definitely never duplicate the state in multiple places as this can create bugs where they get out of sync. The solution is to hoist state and then pass it down via props, see https://beta.reactjs.org/learn/sharing-state-between-components.

Here is your codesandbox modified as an example: https://codesandbox.io/s/keen-wilbur-0xyi8f

CodePudding user response:

You are duplicating the sate multiple times, plus there are some unnecessary helper functions along the way.

The state can be held in one place, with its setter function passed to the toolbar component, like so:

export default function App() {
  const [searchStr, setSearchStr] = useState("");
  return (
    <div className="App">
      <h1>Tony Starks Nicknames</h1>
      <Toolbar searchStr={searchStr} onSearchStrChange={setSearchStr} />
      <List searchStr={searchStr} />
    </div>
  );
}

Then, the toolbar can look like this:

function Toolbar({ searchStr, onSearchStrChange }) {
  const handleChange = (e) => {
    onSearchStrChange(e.target.value);
  };

  return (
    <div>
      <input
        type="text"
        onChange={handleChange}
        value={searchStr}
        placeholder="search..."
      />
    </div>
  );
}

This way, there's only one place where the state is stored

CodePudding user response:

If your hierarchy's depth is or might become greater than 2, I would suggest the Context API.

https://reactjs.org/docs/context.html

  • Related