简体   繁体   中英

Should i pass react hooks as a value to Context Provider?

I need global variable users that is able to filtering out some users. Using react hooks passed as a value leading to rerendering page many times. Which solution is better and why?

    export const UsersProvider = props => {
  const [user, setUser] = useState({
    isLogged: false
  });

  return (
    <UsersContext.Provider value={[filteredUsers, setFilteredUsers]}>
{props.children}
    </UsersContext.Provider>
  );
};

OR

class UserProvider extends React.Component {
  constructor(props) {
    super(props);

    this.setUser = () => {
      this.setState(state => {
        return {user: "true"};
      });
      console.log(this.state.user);
    };

    // State also contains the updater function so it will
    // be passed down into the context provider
    this.state = {
      user: false,
      setUser: this.setUser
    };
  }

  render() {
    return (
      <UserContext.Provider value={this.state}>
        {this.props.children}
      </UserContext.Provider>
    );
  }
}

You only need to add what you need to use in a consumer. Personally I only supply a couple functions/values like this:

export const UsersProvider = props => {
  const [user, setUser] = useState({
    isLogged: false
  });

  const props = {
    filteredUsers,
    setFilteredUsers
  };

  return (
    <UsersContext.Provider {...props}>
      {props.children}
    </UsersContext.Provider>
  );
};

But I'd only add the things you need elsewhere to the props object. I doubt you need everything on your current component's state elsewhere because if you do, you may have an organization problem.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM