Redux can be intimidating and has a reputation for being hard to implement at first, but it doesn’t have to be! This simple example can help you navigate the murky waters, avoid pitfalls, and get started with Redux!

There’s a nice selection of options out there for managing state in React, and the solution you choose will be based on a number of factors (for example, the size and complexity of your application). This article focuses on a very specific use case and allows you to get your feet wet by refactoring a simple application to include Redux.

There’s a lot to learn from taking a fully functional application and purposefully breaking it in order to improve and grow. I gave a Lightning talk on Redux while at Hackbright Academy, and decided to refactor a short and sweet (well, maybe not so sweet 😳) app we used in a lab, called Sharkwords. The app is a hangman-style game that results in the character’s early demise if the secret word is not selected in under five guesses. Watch out for sharks…

Step 1. Gather Your State and Set Up Your Store

In Redux, the createStore function creates an object, the “store,” that holds the application state for the entire app. It’s possible to shove every piece of state in there, but it’s not absolutely necessary (if you prefer, you can manage state that’s local to a component with the useState hook instead). In this example, we store the following state in the store:

  • numWrong (i.e. the number of incorrect guesses)
  • guessedLetters(i.e. which letters of the alphabet have been guessed)
  • word (secret word hardcoded to “hello” for this simple example)

First, declare your initial state when starting a fresh game and create your store:

const { Provider, useSelector, useDispatch } = ReactRedux;

const initialState = {
  numWrong: 0,
  guessedLetters: [],
  word: 'hello',
};

...

// Create a Redux store holding the state of your app.

const store = Redux.createStore(
  reducer,
  window.__REDUX_DEVTOOLS_EXTENSION__ && window.__REDUX_DEVTOOLS_EXTENSION__()
);

// Wrap in <Provider> tags to access the store throughout the app

ReactDOM.render(
  <Provider store={store}>
    <Sharkwords />
  </Provider>,
  document.querySelector('#root')
);

Step 2. Let’s See Some Action(s)!

It’s important to remember that the store is immutable, meaning it can’t be changed directly. So when the state changes in the app, a new state object is created (i.e., a copy is made with the minor change in it). To achieve these changes—for example when a user guesses a letter—we use actions and **reducers **(don’t worry, I’ll explain that in a bit). So let’s go ahead and declare two actions in our game:


...

const GUESS_LETTER = 'GUESS_LETTER';
const RESET = 'RESET';

...

Pretty straightforward: the user can guess a letter, GUESS_LETTER, or reset the game, RESET .

#react #redux #javascript #web-development #developer

Hooked on React Redux
2.25 GEEK