DEV Community

Discussion on: It's OK to useStore with React-Redux

Collapse
 
markerikson profile image
Mark Erikson • Edited

Yeah, "use a value that isn't going to change" is a relatively rare use case. In most cases people do want to get updates, and part of the point of that warning I wrote is that some folks have tried to call store.getState() without realizing that it will not re-render the component when there's a change.

Note that in cases where you need to access Redux state in a callback, that may be a good use case for just moving all that logic into a thunk, since thunks have access to getState.

FWIW, you can actually (ab)use dispatch to implement the "read but not subscribe" use case, by having passing a selector to a thunk, then having the thunk immediately return the selector result :)

const selectTodos = state => state.todos;

const readSomeState = (selector) => {
  return (dispatch, getState) => {
    return selector(getState());
  }
}

// later
function MyComponent() {
  const dispatch = useDispatch();

  // THIS IS HACKY, and yet it works, legally!
  const todos = dispatch(readSomeState(selectTodos));

  // render here
}
Enter fullscreen mode Exit fullscreen mode

I'm not sure I necessarily recommend this approach, but it's syntactically and semantically valid.

Collapse
 
dylangrandmont profile image
Dylan Grandmont

Thanks for taking a look at the post @markerikson ! I was considering making a PR to the react-redux docs to update the wording but it sounds like in general this is not a common use case for users.

Collapse
 
dominikdosoudil profile image
Dominik Dosoudil

I think that thunk (or saga) won't cover all cases. Sometimes you don't need global state and you are just fine with useState. In that case you can't use thunk to access the store and useStore is the best option IMO.

Collapse
 
markerikson profile image
Mark Erikson

I.... have no idea what you're trying to say there.

The article is discussing the React-Redux useStore hook. useState has nothing to do with this.

Sagas aren't even part of this discussion.

Thread Thread
 
dominikdosoudil profile image
Dominik Dosoudil

I am talking about following scenario. In case you want get data from store, do something with them on demand (user click) and save them into local store, you cannot use thunk. I know that I might store it into redux instead of local state, but sometimes it's just better option.


const Foo = () => {
  const [computed, setComputed] = useState(0);
  const store = useStore();
  const recompute = useCallback(() => {
    const data = store.getState();
    setComputed(doSomething(data));
  });
  return <>...</>
};
Enter fullscreen mode Exit fullscreen mode

Did I make my point clear?