Blog>
Snippets

Object.create(null) in Redux selectors for safer state access

Utilize Redux selectors to access state properties on objects created with Object.create(null), avoiding accidental prototype access.
const initialState = Object.create(null); // create a state object with no prototype
initialState.someData = { value: 0 };

function rootReducer(state = initialState, action) {
  // reducer logic here
  return state;
}
This is the root reducer with an `initialState` that is created using `Object.create(null)` to have a truly empty object with no prototype, and a property `someData` is added to it. Using a prototype-free object as a state ensures that the state doesn't inherit any properties from the default object prototype, such as `toString` or `hasOwnProperty`, which can protect against prototype pollution attacks and other accidental property accesses.
function selectSomeData(state) {
  return state.someData;
}

// Later in the code, typically in a React component
// const someData = useSelector(selectSomeData);
This is a selector function that safely accesses the `someData` property from the state. Since the state is created with `Object.create(null)`, there is no need to worry about accidentally accessing a property from the object's prototype. This selector can be used with the `useSelector` hook from `react-redux` to access `someData` in a React component.
<!DOCTYPE html>
<html>
<head>
  <title>Redux Selector Example</title>
  <style>
    /* CSS styles can be added here if needed */
  </style>
</head>
<body>
  <div id="app"></div>
  <!-- Here you would include your JavaScript bundles that use Redux and the defined selectors -->
  <script src="path-to-your-redux-bundle.js"></script>
</body>
</html>
This is a basic HTML structure where a Redux application would be mounted. The script tag at the bottom of the body should link to the JavaScript file that includes Redux and the selectors defined above. The Redux state will be used through selectors within React components which can be rendered inside the 'app' div. This ensures that the application is structured properly and the Redux state is accessed in a safe and controlled manner.