D
D
Durin Qurkingo2019-07-26 07:11:53
React
Durin Qurkingo, 2019-07-26 07:11:53

How to use useStore, useSelector, useDispatch hook?

New hooks have been released with Redux version 7.1.0. I don't understand how to use these hooks in practice. Can someone give an example of using these hooks?

Answer the question

In order to leave comments, you need to log in

1 answer(s)
A
Anton Spirin, 2019-07-26
@Sagund

1. useDispatch - getting the store.dispatch function in the component. Previously, to call an action, a functional component had to be wrapped in a connect call:

const Foo = ({ dispatch }) => {
  const handler = useCallback(() => {
    dispatch(action());
  }, []);

  return (
    <Bar onClick={handler} />
  );
};

export default connect()(Foo);

Now:
const Foo = () => {
  const dispatch = useDispatch();

  const handler = useCallback(() => {
    dispatch(action());
  }, []);

  return (
    <Bar onClick={handler} />
  );
};

export default Foo;

2. useSelector - mapping value from store.
Before:
const Foo = ({ value }) => {
  return (
    <Bar value={value} />
  );
};

const mapStateToProps = state => ({
  value: state.value,
});

export default connect(mapStateToProps)(Foo);

const Foo = () => {
  const value = useSelector(state => state.value);

  return (
    <Bar value={value} />
  );
};

export default Foo;

3. useStore - getting the whole store:
const valueSelector = state => state.value;

const Foo = () => {
  const { dispatch, getState, subscribe } = useStore();
  const value = valueSelector(getState());
  
  useEffect(() => subscribe(console.log), []);

  const handler = useCallback(() => {
    dispatch(action());
  }, []);

  return (
    <Bar onClick={handler} value={value} />
  );
};

export default Foo;

It is unlikely that you really need useStore in practice.

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question